绿茶有什么好处| 貔貅是什么生肖| 本来无一物何处惹尘埃是什么意思| 水痘通过什么途径传染| 血糖高可以吃什么蔬菜| 送什么礼物好| 泡打粉可以用什么代替| 无花果叶子有什么功效| 前列腺炎吃什么药好| 罗汉果有什么功效和作用| 冷冻跟冷藏有什么区别| 甲状腺4a类什么意思| 眼睛干痒用什么眼药水比较好| 为什么会气虚| 双鱼座什么性格| 什么时间运动减肥效果最好| am和pm是什么意思| 嫉妒是什么意思| 吃榴莲不能吃什么东西| 家庭烧烤准备什么食材| 1月6号什么星座| 东宫是什么生肖| pf是什么意思| 呲牙是什么意思| 火险痣是什么意思| 心颤吃什么药效果好| 画什么点睛| 火车无座是什么意思| hk是什么意思| 甲减吃什么食物好| 诬赖是什么意思| 胎停有什么症状| 红加绿等于什么颜色| 糖尿病筛查做什么检查| 同房后小腹痛什么原因| 黑枸杞泡茶是什么颜色| 为什么突然对鸡蛋过敏| 眩晕症是什么原因引起| 属虎适合佩戴什么饰品| 西游记什么朝代写的| 吃什么代谢快有助于减肥| 防代表什么生肖| 什么花粉| 为什么日语| his系统是什么| rpr是什么检查项目| 玫瑰的花语是什么| 肺有小结节要注意什么| 甲钴胺片主治什么病| 心肌炎是什么病严重吗| 颈椎压迫神经吃什么药| r值是什么| 身份证带x是什么意思| 什么的感受| 5月21日是什么星座| 石斛不能和什么一起吃| 低压48有什么危险| 情投意合是什么意思| 什么牌子的麦克风好用| 12月20是什么星座| cd是什么意思| 沉鱼落雁闭月羞花什么意思| 薄荷叶晒干后能干什么| 征字五行属什么| 为什么会得脚气| 10000mah是什么意思| 清鼻涕吃什么药| 瘖什么意思| 读书的意义是什么| 小腹痛吃什么药| 疖肿是什么样子的图片| 甲子年是什么意思| 星期天为什么不叫星期七| 吃无花果有什么好处| 龄字五行属什么| 雨花茶是什么茶| fs是什么意思| 分解酒精的是什么酶| 绿色加什么颜色是蓝色| mi是什么意思| 生冷辛辣指的是什么| 局灶肠化是什么意思| o型血为什么叫贵族血| pu什么意思| 宝宝为什么老是吐奶| 失眠吃什么中成药| 女同叫什么| 鲁肃的性格特点是什么| 蟑螂怕什么| fa是什么| 脑梗的症状是什么| 香蕉什么时候吃最好| 什么是代谢| 骨质疏松有什么症状| 热射病是什么病| 佛性是什么意思| 六月十三日是什么星座| 巨蟹座幸运花是什么| 大什么小什么| 做梦梦到牛是什么意思| 多管闲事是什么意思| 铅是什么东西| 冬天怕冷夏天怕热是什么原因| 老鼠跟什么属相最配| 咳嗽吃什么好的快| 吃什么东西对胃好| 吃什么可以提高免疫力和抵抗力| 痔疮挂什么科| 高血压吃什么助勃药好| 南枝是什么意思| 吃什么止泻| 放射治疗是什么意思| 吃月饼是什么生肖| 心跳过缓吃什么药| 月经推迟吃什么药| 白酒配什么饮料好喝| 血糖高是什么原因造成的| 左边小腹疼是什么原因| 前列腺吃什么药好| 乳腺结节不能吃什么食物| 一代明君功千秋是什么生肖| 钾是什么| 对辣椒过敏有什么症状| 馥字五行属什么| 梦见墙倒了有什么预兆| 新疆为什么天黑的晚| 孕妇吃火龙果有什么好处| 奢望是什么意思| 商鞅变法是什么时期| 榴莲什么样的好| 喝茶叶茶有什么好处| 富丽堂皇是什么意思| 尿频尿急尿不尽吃什么药最快见效| 9年是什么婚| 探病送什么花| loa是什么意思| 站着说话不腰疼什么意思| 叶公好龙告诉我们什么道理| 新生儿溶血是什么意思| 椴树是什么树| 鸭肉和什么一起炖好吃| 颜控是什么意思| 什么动物牙齿最多| 高大的动物是什么生肖| 320是什么意思| 血红素高是什么原因| 脑梗做什么检查| 晶莹的近义词是什么| 阿米替林片是治什么病的| 天天睡不着觉什么原因| 什么是火象星座| 舒坦是什么意思| 创伤急救的原则是什么| 农夫与蛇是什么故事| 嗜碱性粒细胞偏高是什么原因| 一呼吸胸口疼是什么原因| 日皮是什么意思| 吃红萝卜有什么好处| 呕吐吃什么药| 乾字五行属什么| 有点想吐是什么原因| 八点半是什么时辰| 引流是什么意思| 蟑螂为什么叫小强| 阿飞是什么意思| 早期教育是什么| 乳房疼痛应该挂什么科| 正月十六是什么星座| 什么花喜欢磷酸二氢钾| 狗为什么不能吃葡萄| 属相是什么意思| 内胆是什么意思| 酸菜鱼用什么鱼| 牵牛花什么时候开| 10月18日什么星座| 为什么第一次进不去| 金丝熊吃什么| 高压偏低是什么原因造成的| 古代天花是现代什么病| 红花泡水喝有什么功效| 非文念什么| 新疆为什么天黑的晚| 嫑怹是什么意思| bag是什么意思| 肾积水吃什么药最好| 七月十一日是什么日子| 德巴金是什么药| 折耳猫为什么不能养| 头发掉要用什么洗发水| 养胃吃什么最好| 妊娠试验阴性是什么意思| 女生下面长什么样| 无什么不什么的成语| 脂肪瘤看什么科| 胎盘分级0级什么意思| 58年属什么生肖| 羊配什么生肖最好| 脑缺血有什么症状| 我适合什么发型| 卤水是什么水| 飞蛾吃什么东西| 多多益善什么意思| 双鱼座什么性格| 本心是什么意思| 法香是什么菜| 资治通鉴讲的是什么| 尿常规检查什么| 精索静脉曲张是什么意思| 沙棘原浆有什么功效| 蚊子讨厌什么气味| 甲功三项查的是什么| 白发是什么原因引起的| 邮政ems是什么意思| 执业药师证有什么用| 时令是什么意思| 增殖灶是什么意思| 出汗有盐霜是什么原因| 睡觉时头晕是什么原因| g6pd是检查什么的| 黑色的蜂是什么蜂| 丑时属什么| 吃什么可以长高| 海马吃什么| 摩羯座的幸运色是什么| hpv有什么危害| 2013年是什么年| 17号来月经什么时候是排卵期| 喝酒之前吃什么保护胃| 落井下石什么意思| 东莞有什么好玩的地方| 起义是什么意思| 慈禧姓什么| 胃不好的人适合吃什么水果| 染什么颜色| 用什么泡脚可以去湿气| 胎动突然减少是什么原因| 九月七日是什么星座| 烦请是什么意思| 身体缺钾是什么症状| 唏嘘不已的意思是什么| 宝宝上颚有白点是什么| 龙骨是什么骨头| 新生儿甲状腺偏高有什么影响| 弹性工作制是什么意思| 11月17是什么星座| 东盟为什么没有中国| 嵌合体是什么意思| alyx是什么牌子| 什么是肾癌| 精神小伙什么意思| 狗狗胰腺炎吃什么药| 忠心不二是什么生肖| 头部mra是什么检查| 04年是什么生肖| 印堂发红是什么的征兆| 尿结石是什么引起的| 五月是什么生肖| 2009属什么生肖| 石头记为什么叫红楼梦| od值是什么意思| 二黑是什么意思| 护理专业主要学什么| 豆腐吃多了有什么坏处| grader是什么意思| 百度
    1. 8.6 Timers
    2. 8.7 Microtask queuing
    3. 8.8 User prompts
      1. 8.8.1 Simple dialogs
      2. 8.8.2 Printing

8.6 Timers

The setTimeout() and setInterval() methods allow authors to schedule timer-based callbacks.

id = self.setTimeout(handler [, timeout [, ...arguments ] ])

setTimeout

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera4+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android10.1+

Schedules a timeout to run handler after timeout milliseconds. Any arguments are passed straight through to the handler.

id = self.setTimeout(code [, timeout ])

Schedules a timeout to compile and run code after timeout milliseconds.

self.clearTimeout(id)

clearTimeout

Support in all current engines.

Firefox1+Safari4+Chrome1+
Opera4+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android?Safari iOS1+Chrome Android?WebView Android37+Samsung Internet?Opera Android10.1+

Cancels the timeout set with setTimeout() or setInterval() identified by id.

id = self.setInterval(handler [, timeout [, ...arguments ] ])

setInterval

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera4+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android10.1+

Schedules a timeout to run handler every timeout milliseconds. Any arguments are passed straight through to the handler.

id = self.setInterval(code [, timeout ])

Schedules a timeout to compile and run code every timeout milliseconds.

self.clearInterval(id)

clearInterval

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera4+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android?Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android10.1+

Cancels the timeout set with setInterval() or setTimeout() identified by id.

Timers can be nested; after five such nested timers, however, the interval is forced to be at least four milliseconds.

This API does not guarantee that timers will run exactly on schedule. Delays due to CPU load, other tasks, etc, are to be expected.

Objects that implement the WindowOrWorkerGlobalScope mixin have a map of setTimeout and setInterval IDs, which is an ordered map, initially empty. Each key in this map is a positive integer, corresponding to the return value of a setTimeout() or setInterval() call. Each value is a unique internal value, corresponding to a key in the object's map of active timers.


The setTimeout(handler, timeout, ...arguments) method steps are to return the result of running the timer initialization steps given this, handler, timeout, arguments, and false.

The setInterval(handler, timeout, ...arguments) method steps are to return the result of running the timer initialization steps given this, handler, timeout, arguments, and true.

The clearTimeout(id) and clearInterval(id) method steps are to remove this's map of setTimeout and setInterval IDs[id].

Because clearTimeout() and clearInterval() clear entries from the same map, either method can be used to clear timers created by setTimeout() or setInterval().


To perform the timer initialization steps, given a WindowOrWorkerGlobalScope global, a string or Function or TrustedScript handler, a number timeout, a list arguments, a boolean repeat, and optionally (and only if repeat is true) a number previousId, perform the following steps. They return a number.

  1. Let thisArg be global if that is a WorkerGlobalScope object; otherwise let thisArg be the WindowProxy that corresponds to global.

  2. If previousId was given, let id be previousId; otherwise, let id be an implementation-defined integer that is greater than zero and does not already exist in global's map of setTimeout and setInterval IDs.

  3. If the surrounding agent's event loop's currently running task is a task that was created by this algorithm, then let nesting level be the task's timer nesting level. Otherwise, let nesting level be 0.

    The task's timer nesting level is used both for nested calls to setTimeout(), and for the repeating timers created by setInterval(). (Or, indeed, for any combination of the two.) In other words, it represents nested invocations of this algorithm, not of a particular method.

  4. If timeout is less than 0, then set timeout to 0.

  5. If nesting level is greater than 5, and timeout is less than 4, then set timeout to 4.

  6. Let realm be global's relevant realm.

  7. Let initiating script be the active script.

  8. Let uniqueHandle be null.

  9. Let task be a task that runs the following substeps:

    1. Assert: uniqueHandle is a unique internal value, not null.

    2. If id does not exist in global's map of setTimeout and setInterval IDs, then abort these steps.

    3. If global's map of setTimeout and setInterval IDs[id] does not equal uniqueHandle, then abort these steps.

      This accommodates for the ID having been cleared by a clearTimeout() or clearInterval() call, and being reused by a subsequent setTimeout() or setInterval() call.

    4. Record timing info for timer handler given handler, global's relevant settings object, and repeat.

    5. If handler is a Function, then invoke handler given arguments and "report", and with callback this value set to thisArg.

    6. Otherwise:

      1. If previousId was not given:

        1. Let globalName be "Window" if global is a Window object; "WorkerGlobalScope" otherwise.

        2. Let methodName be "setInterval" if repeat is true; "setTimeout" otherwise.

        3. Let sink be a concatenation of globalName, U+0020 SPACE, and methodName.

        4. Set handler to the result of invoking the Get Trusted Type compliant string algorithm with TrustedScript, global, handler, sink, and "script".

      2. Assert: handler is a string.

      3. Perform EnsureCSPDoesNotBlockStringCompilation(realm, ? ?, handler, handler, timer, ? ?, handler). If this throws an exception, catch it, report it for global, and abort these steps.

      4. Let settings object be global's relevant settings object.

      5. Let fetch options be the default script fetch options.

      6. Let base URL be settings object's API base URL.

      7. If initiating script is not null, then:

        1. Set fetch options to a script fetch options whose cryptographic nonce is initiating script's fetch options's cryptographic nonce, integrity metadata is the empty string, parser metadata is "not-parser-inserted", credentials mode is initiating script's fetch options's credentials mode, referrer policy is initiating script's fetch options's referrer policy, and fetch priority is "auto".

        2. Set base URL to initiating script's base URL.

        The effect of these steps ensures that the string compilation done by setTimeout() and setInterval() behaves equivalently to that done by eval(). That is, module script fetches via import() will behave the same in both contexts.

      8. Let script be the result of creating a classic script given handler, settings object, base URL, and fetch options.

      9. Run the classic script script.

    7. If id does not exist in global's map of setTimeout and setInterval IDs, then abort these steps.

    8. If global's map of setTimeout and setInterval IDs[id] does not equal uniqueHandle, then abort these steps.

      The ID might have been removed via the author code in handler calling clearTimeout() or clearInterval(). Checking that uniqueHandle isn't different accounts for the possibility of the ID, after having been cleared, being reused by a subsequent setTimeout() or setInterval() call.

    9. If repeat is true, then perform the timer initialization steps again, given global, handler, timeout, arguments, true, and id.

    10. Otherwise, remove global's map of setTimeout and setInterval IDs[id].

  10. Increment nesting level by one.

  11. Set task's timer nesting level to nesting level.

  12. Let completionStep be an algorithm step which queues a global task on the timer task source given global to run task.

  13. Set uniqueHandle to the result of running steps after a timeout given global, "setTimeout/setInterval", timeout, and completionStep.

  14. Set global's map of setTimeout and setInterval IDs[id] to uniqueHandle.

  15. Return id.

Argument conversion as defined by Web IDL (for example, invoking toString() methods on objects passed as the first argument) happens in the algorithms defined in Web IDL, before this algorithm is invoked.

So for example, the following rather silly code will result in the log containing "ONE?TWO?":

var log = '';
function logger(s) { log += s + ' '; }

setTimeout({ toString: function () {
  setTimeout("logger('ONE')", 100);
  return "logger('TWO')";
} }, 100);

To run tasks of several milliseconds back to back without any delay, while still yielding back to the browser to avoid starving the user interface (and to avoid the browser killing the script for hogging the CPU), simply queue the next timer before performing work:

function doExpensiveWork() {
  var done = false;
  // ...
  // this part of the function takes up to five milliseconds
  // set done to true if we're done
  // ...
  return done;
}

function rescheduleWork() {
  var id = setTimeout(rescheduleWork, 0); // preschedule next iteration
  if (doExpensiveWork())
    clearTimeout(id); // clear the timeout if we don't need it
}

function scheduleWork() {
  setTimeout(rescheduleWork, 0);
}

scheduleWork(); // queues a task to do lots of work

Objects that implement the WindowOrWorkerGlobalScope mixin have a map of active timers, which is an ordered map, initially empty. Each key in this map is a unique internal value that represents a timer, and each value is a DOMHighResTimeStamp, representing the expiry time for that timer.

To run steps after a timeout, given a WindowOrWorkerGlobalScope global, a string orderingIdentifier, a number milliseconds, and a set of steps completionSteps, perform the following steps. They return a unique internal value.

  1. Let timerKey be a new unique internal value.

  2. Let startTime be the current high resolution time given global.

  3. Set global's map of active timers[timerKey] to startTime plus milliseconds.

  4. Run the following steps in parallel:

    1. If global is a Window object, wait until global's associated Document has been fully active for a further milliseconds milliseconds (not necessarily consecutively).

      Otherwise, global is a WorkerGlobalScope object; wait until milliseconds milliseconds have passed with the worker not suspended (not necessarily consecutively).

    2. Wait until any invocations of this algorithm that had the same global and orderingIdentifier, that started before this one, and whose milliseconds is less than or equal to this one's, have completed.

    3. Optionally, wait a further implementation-defined length of time.

      This is intended to allow user agents to pad timeouts as needed to optimize the power usage of the device. For example, some processors have a low-power mode where the granularity of timers is reduced; on such platforms, user agents can slow timers down to fit this schedule instead of requiring the processor to use the more accurate mode with its associated higher power usage.

    4. Perform completionSteps.

    5. Remove global's map of active timers[timerKey].

  5. Return timerKey.

Run steps after a timeout is meant to be used by other specifications that want to execute developer-supplied code after a developer-supplied timeout, in a similar manner to setTimeout(). (Note, however, it does not have the nesting and clamping behavior of setTimeout().) Such specifications can choose an orderingIdentifier to ensure ordering within their specification's timeouts, while not constraining ordering with respect to other specification's timeouts.

8.7 Microtask queuing

queueMicrotask

Support in all current engines.

Firefox69+Safari12.1+Chrome71+
Opera?Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
self.queueMicrotask(callback)

Queues a microtask to run the given callback.

The queueMicrotask(callback) method must queue a microtask to invoke callback with ? ? and "report".

The queueMicrotask() method allows authors to schedule a callback on the microtask queue. This allows their code to run once the JavaScript execution context stack is next empty, which happens once all currently executing synchronous JavaScript has run to completion. This doesn't yield control back to the event loop, as would be the case when using, for example, setTimeout(f,?0).

Authors ought to be aware that scheduling a lot of microtasks has the same performance downsides as running a lot of synchronous code. Both will prevent the browser from doing its own work, such as rendering. In many cases, requestAnimationFrame() or requestIdleCallback() is a better choice. In particular, if the goal is to run code before the next rendering cycle, that is the purpose of requestAnimationFrame().

As can be seen from the following examples, the best way of thinking about queueMicrotask() is as a mechanism for rearranging synchronous code, effectively placing the queued code immediately after the currently executing synchronous JavaScript has run to completion.

The most common reason for using queueMicrotask() is to create consistent ordering, even in the cases where information is available synchronously, without introducing undue delay.

For example, consider a custom element firing a load event, that also maintains an internal cache of previously-loaded data. A na?ve implementation might look like:

MyElement.prototype.loadData = function (url) {
  if (this._cache[url]) {
    this._setData(this._cache[url]);
    this.dispatchEvent(new Event("load"));
  } else {
    fetch(url).then(res => res.arrayBuffer()).then(data => {
      this._cache[url] = data;
      this._setData(data);
      this.dispatchEvent(new Event("load"));
    });
  }
};

This na?ve implementation is problematic, however, in that it causes its users to experience inconsistent behavior. For example, code such as

element.addEventListener("load", () => console.log("loaded"));
console.log("1");
element.loadData();
console.log("2");

will sometimes log "1, 2, loaded" (if the data needs to be fetched), and sometimes log "1, loaded, 2" (if the data is already cached). Similarly, after the call to loadData(), it will be inconsistent whether or not the data is set on the element.

To get a consistent ordering, queueMicrotask() can be used:

MyElement.prototype.loadData = function (url) {
  if (this._cache[url]) {
    queueMicrotask(() => {
      this._setData(this._cache[url]);
      this.dispatchEvent(new Event("load"));
    });
  } else {
    fetch(url).then(res => res.arrayBuffer()).then(data => {
      this._cache[url] = data;
      this._setData(data);
      this.dispatchEvent(new Event("load"));
    });
  }
};

By essentially rearranging the queued code to be after the JavaScript execution context stack empties, this ensures a consistent ordering and update of the element's state.

Another interesting use of queueMicrotask() is to allow uncoordinated "batching" of work by multiple callers. For example, consider a library function that wants to send data somewhere as soon as possible, but doesn't want to make multiple network requests if doing so is easily avoidable. One way to balance this would be like so:

const queuedToSend = [];

function sendData(data) {
  queuedToSend.push(data);

  if (queuedToSend.length === 1) {
    queueMicrotask(() => {
      const stringToSend = JSON.stringify(queuedToSend);
      queuedToSend.length = 0;

      fetch("/endpoint", stringToSend);
    });
  }
}

With this architecture, multiple subsequent calls to sendData() within the currently executing synchronous JavaScript will be batched together into one fetch() call, but with no intervening event loop tasks preempting the fetch (as would have happened with similar code that instead used setTimeout()).

8.8 User prompts

8.8.1 Simple dialogs

window.alert(message)

Window/alert

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera3+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android10.1+

Displays a modal alert with the given message, and waits for the user to dismiss it.

result = window.confirm(message)

Window/confirm

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera3+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android?Safari iOS?Chrome Android?WebView Android1+Samsung Internet?Opera Android10.1+

Displays a modal OK/Cancel prompt with the given message, waits for the user to dismiss it, and returns true if the user clicks OK and false if the user clicks Cancel.

result = window.prompt(message [, default])

Window/prompt

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera3+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android10.1+

Displays a modal text control prompt with the given message, waits for the user to dismiss it, and returns the value that the user entered. If the user cancels the prompt, then returns null instead. If the second argument is present, then the given value is used as a default.

Logic that depends on tasks or microtasks, such as media elements loading their media data, are stalled when these methods are invoked.

The alert() and alert(message) method steps are:

  1. If we cannot show simple dialogs for this, then return.

  2. If the method was invoked with no arguments, then let message be the empty string; otherwise, let message be the method's first argument.

  3. Set message to the result of normalizing newlines given message.

  4. Set message to the result of optionally truncating message.

  5. Let userPromptHandler be WebDriver BiDi user prompt opened with this, "alert", and message.

  6. If userPromptHandler is "none", then:

    1. Show message to the user, treating U+000A LF as a line break.

    2. Optionally, pause while waiting for the user to acknowledge the message.

  7. Invoke WebDriver BiDi user prompt closed with this, "alert", and true.

This method is defined using two overloads, instead of using an optional argument, for historical reasons. The practical impact of this is that alert(undefined) is treated as alert("undefined"), but alert() is treated as alert("").

The confirm(message) method steps are:

  1. If we cannot show simple dialogs for this, then return false.

  2. Set message to the result of normalizing newlines given message.

  3. Set message to the result of optionally truncating message.

  4. Show message to the user, treating U+000A LF as a line break, and ask the user to respond with a positive or negative response.

  5. Let userPromptHandler be WebDriver BiDi user prompt opened with this, "confirm", and message.

  6. Let accepted be false.

  7. If userPromptHandler is "none", then:

    1. Pause until the user responds either positively or negatively.

    2. If the user responded positively, then set accepted to true.

  8. If userPromptHandler is "accept", then set accepted to true.

  9. Invoke WebDriver BiDi user prompt closed with this, "confirm", and accepted.

  10. Return accepted.

The prompt(message, default) method steps are:

  1. If we cannot show simple dialogs for this, then return null.

  2. Set message to the result of normalizing newlines given message.

  3. Set message to the result of optionally truncating message.

  4. Set default to the result of optionally truncating default.

  5. Show message to the user, treating U+000A LF as a line break, and ask the user to either respond with a string value or abort. The response must be defaulted to the value given by default.

  6. Let userPromptHandler be WebDriver BiDi user prompt opened with this, "prompt", and message.

  7. Let result be null.

  8. If userPromptHandler is "none", then:

    1. Pause while waiting for the user's response.

    2. If the user did not abort, then set result to the string that the user responded with.

  9. Otherwise, if userPromptHandler is "accept", then set result to the empty string.

  10. Invoke WebDriver BiDi user prompt closed with this, "prompt", false if result is null or true otherwise, and result.

  11. Return result.

To optionally truncate a simple dialog string s, return either s itself or some string derived from s that is shorter. User agents should not provide UI for displaying the elided portion of s, as this makes it too easy for abusers to create dialogs of the form "Important security alert! Click 'Show More' for full details!".

For example, a user agent might want to only display the first 100 characters of a message. Or, a user agent might replace the middle of the string with "…". These types of modifications can be useful in limiting the abuse potential of unnaturally large, trustworthy-looking system dialogs.

We cannot show simple dialogs for a Window window when the following algorithm returns true:

  1. If the active sandboxing flag set of window's associated Document has the sandboxed modals flag set, then return true.

  2. If window's relevant settings object's origin and window's relevant settings object's top-level origin are not same origin-domain, then return true.

  3. If window's relevant agent's event loop's termination nesting level is nonzero, then optionally return true.
  4. Optionally, return true. (For example, the user agent might give the user the option to ignore all modal dialogs, and would thus abort at this step whenever the method was invoked.)

  5. Return false.

8.8.2 Printing

Window/print

Support in all current engines.

Firefox1+Safari1.1+Chrome1+
Opera6+Edge79+
Edge (Legacy)12+Internet Explorer5+
Firefox Android114+Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android10.1+
window.print()

Prompts the user to print the page.

The print() method steps are:

  1. Let document be this's associated Document.

  2. If document is not fully active, then return.

  3. If document's unload counter is greater than 0, then return.

  4. If document is ready for post-load tasks, then run the printing steps for document.

  5. Otherwise, set document's print when loaded flag.

User agents should also run the printing steps whenever the user asks for the opportunity to obtain a physical form (e.g. printed copy), or the representation of a physical form (e.g. PDF copy), of a document.

The printing steps for a Document document are:

  1. The user agent may display a message to the user or return (or both).

    For instance, a kiosk browser could silently ignore any invocations of the print() method.

    For instance, a browser on a mobile device could detect that there are no printers in the vicinity and display a message saying so before continuing to offer a "save to PDF" option.

  2. If the active sandboxing flag set of document has the sandboxed modals flag set, then return.

    If the printing dialog is blocked by a Document's sandbox, then neither the beforeprint nor afterprint events will be fired.

  3. The user agent must fire an event named beforeprint at the relevant global object of document, as well as any child navigable in it.

    Firing in children only doesn't seem right here, and some tasks likely need to be queued. See issue #5096.

    The beforeprint event can be used to annotate the printed copy, for instance adding the time at which the document was printed.

  4. The user agent should offer the user the opportunity to obtain a physical form (or the representation of a physical form) of document. The user agent may wait for the user to either accept or decline before returning; if so, the user agent must pause while the method is waiting. Even if the user agent doesn't wait at this point, the user agent must use the state of the relevant documents as they are at this point in the algorithm if and when it eventually creates the alternate form.

  5. The user agent must fire an event named afterprint at the relevant global object of document, as well as any child navigables in it.

    Firing in children only doesn't seem right here, and some tasks likely need to be queued. See issue #5096.

    The afterprint event can be used to revert annotations added in the earlier event, as well as showing post-printing UI. For instance, if a page is walking the user through the steps of applying for a home loan, the script could automatically advance to the next step after having printed a form or other.

百度