1. 8 Web application APIs
    1. 8.1 Scripting
      1. 8.1.1 Introduction
      2. 8.1.2 Enabling and disabling scripting
      3. 8.1.3 Processing model
        1. 8.1.3.1 Definitions
        2. 8.1.3.2 Fetching scripts
        3. 8.1.3.3 Creating scripts
        4. 8.1.3.4 Calling scripts
        5. 8.1.3.5 Realms, settings objects, and global objects
          1. 8.1.3.5.1 Entry
          2. 8.1.3.5.2 Incumbent
          3. 8.1.3.5.3 Current
          4. 8.1.3.5.4 Relevant
        6. 8.1.3.6 Killing scripts
        7. 8.1.3.7 Integration with the JavaScript job queue
          1. 8.1.3.7.1 EnqueueJob(queueName, job, arguments)
        8. 8.1.3.8 Integration with the JavaScript module system
          1. 8.1.3.8.1 HostResolveImportedModule(referencingModule, specifier)
        9. 8.1.3.9 Runtime script errors
          1. 8.1.3.9.1 Runtime script errors in documents
          2. 8.1.3.9.2 The ErrorEvent interface
        10. 8.1.3.10 Unhandled promise rejections
          1. 8.1.3.10.1 HostPromiseRejectionTracker(promise, operation)
          2. 8.1.3.10.2 The PromiseRejectionEvent interface
        11. 8.1.3.11 HostEnsureCanCompileStrings(callerRealm, calleeRealm)
      4. 8.1.4 Event loops
        1. 8.1.4.1 Definitions
        2. 8.1.4.2 Processing model
        3. 8.1.4.3 Generic task sources
      5. 8.1.5 Events
        1. 8.1.5.1 Event handlers
        2. 8.1.5.2 Event handlers on elements, Document objects, and Window objects
          1. 8.1.5.2.1 IDL definitions
        3. 8.1.5.3 Event firing
    2. 8.2 The WindowOrWorkerGlobalScope mixin
    3. 8.3 Base64 utility methods
    4. 8.4 Dynamic markup insertion
      1. 8.4.1 Opening the input stream
      2. 8.4.2 Closing the input stream
      3. 8.4.3 document.write()
      4. 8.4.4 document.writeln()
    5. 8.5 Timers
    6. 8.6 User prompts
      1. 8.6.1 Simple dialogs
      2. 8.6.2 Printing
    7. 8.7 System state and capabilities
      1. 8.7.1 The Navigator object
        1. 8.7.1.1 Client identification
        2. 8.7.1.2 Language preferences
        3. 8.7.1.3 Custom scheme and content handlers: the registerProtocolHandler() and registerContentHandler() methods
          1. 8.7.1.3.1 Security and privacy
          2. 8.7.1.3.2 Sample user interface
        4. 8.7.1.4 Cookies
        5. 8.7.1.5 Plugins
    8. 8.8 Images
    9. 8.9 Animation Frames

8 Web application APIs

8.1 Scripting

8.1.1 Introduction

Various mechanisms can cause author-provided executable code to run in the context of a document. These mechanisms include, but are probably not limited to:

8.1.2 Enabling and disabling scripting

Scripting is enabled in a browsing context when all of the following conditions are true:

Scripting is disabled in a browsing context when any of the above conditions are false (i.e. when scripting is not enabled).


Scripting is enabled for a node if the node's node document has a browsing context, and scripting is enabled in that browsing context.

Scripting is disabled for a node if there is no such browsing context, or if scripting is disabled in that browsing context.

8.1.3 Processing model

8.1.3.1 Definitions

A script is one of two possible structures. All scripts have:

A settings object

An environment settings object, containing various settings that are shared with other scripts in the same context.

A classic script is a script that has the following additional fields:

Source text

A string containing a block of executable code to be evaluated as a JavaScript Script.

Optionally, a muted errors flag

A flag which, if set, means that error information will not be provided for errors in this script (used to mute errors for cross-origin scripts, since that can leak private information).

A module script is a script that has the following additional fields:

A module record

A Source Text Module Record representing the parsed module, ready to be evaluated.

A base URL

A base URL used for resolving module specifiers when resolving a module specifier. This will either be the URL from which the script was obtained, for external module scripts, or the document base URL of the containing document, for inline module scripts.

An instantiation state

One of "uninstantiated", "errored", or "instantiated", used to prevent reinvocation of ModuleDeclarationInstantiation on modules that failed to instantiate previously.

An instantiation error

A JavaScript value, which has meaning only if the instantiation state is "errored".

A credentials mode

A credentials mode used to fetch imported modules.

A cryptographic nonce

A cryptographic nonce used to fetch imported modules.

A parser state

The parser metadata used to fetch imported modules.


An environment is an object that identifies the settings of a current or potential execution environment. An environment has the following fields:

An id

An opaque string that uniquely identifies the environment.

A creation URL

An absolute URL that represents the location of the resource with which the environment is associated.

In the case of an environment settings object, this URL might be distinct from the environment settings object's responsible document's URL, due to mechanisms such as history.pushState().

A target browsing context

Null or a target browsing context for a navigation request.

An active service worker

Null or a service worker that controls the environment.

An execution ready flag

A flag that indicates whether the environment setup is done. It is initially unset.

An environment settings object is an environment that additionally specifies algorithms for:

A realm execution context

A JavaScript execution context shared by all scripts that use this settings object, i.e. all scripts in a given JavaScript realm. When we run a classic script or run a module script, this execution context becomes the top of the JavaScript execution context stack, on top of which another execution context specific to the script in question is pushed. (This setup ensures ParseScript and ModuleEvaluation know which Realm to use.)

A module map

A module map that is used when importing JavaScript modules.

A responsible browsing context

A browsing context that is assigned responsibility for actions taken by the scripts that use this environment settings object.

When a script creates and navigates a new top-level browsing context, the opener attribute of the new browsing context's Window object will be set to the responsible browsing context's WindowProxy object.

A responsible event loop

An event loop that is used when it would not be immediately clear what event loop to use.

A responsible document

A Document that is assigned responsibility for actions taken by the scripts that use this environment settings object.

For example, the URL of the responsible document is used to set the URL of the Document after it has been reset using document.open().

If the responsible event loop is not a browsing context event loop, then the environment settings object has no responsible document.

An API URL character encoding

A character encoding used to encode URLs by APIs called by scripts that use this environment settings object.

An API base URL

A URL used by APIs called by scripts that use this environment settings object to parse URLs.

An origin

An origin used in security checks.

An HTTPS state

An HTTPS state value representing the security properties of the network channel used to deliver the resource with which the environment settings object is associated.

A referrer policy

The default referrer policy for fetches performed using this environment settings object as a request client. [REFERRERPOLICY]

An environment settings object also has an outstanding rejected promises weak set and an about-to-be-notified rejected promises list, used to track unhandled promise rejections. The outstanding rejected promises weak set must not create strong references to any of its members, and implementations are free to limit its size, e.g. by removing old entries from it when new ones are added.

8.1.3.2 Fetching scripts

This section introduces a number of algorithms for fetching scripts, taking various necessary inputs and resulting in classic or module scripts.

The algorithms below can be customized by optionally supplying a custom perform the fetch hook, which takes a request and an is top-level flag. The algorithm must complete with a response (which may be a network error), either synchronously (when using fetch a classic worker-imported script) or asynchronously (otherwise). The is top-level flag will be set for all classic script fetches, and for the initial fetch when fetching a module script graph or fetching a module worker script graph, but not for the fetches resulting from import statements encountered throughout the graph.

By default, not supplying the perform the fetch will cause the below algorithms to simply fetch the given request, with algorithm-specific customizations to the request and validations of the resulting response.

To layer your own customizations on top of these algorithm-specific ones, supply a perform the fetch hook that modifies the given request, fetches it, and then performs specific validations of the resulting response (completing with a network error if the validations fail).

The hook can also be used to perform more subtle customizations, such as keeping a cache of responses and avoiding performing a fetch at all.

Service Workers is an example of a specification that runs these algorithms with its own options for the hook. [SW]

To fetch a classic script given a url, a settings object, a cryptographic nonce, an integrity metadata, a parser state, a CORS setting, and a character encoding, run these steps. The algorithm will asynchronously complete with either null (on failure) or a new classic script (on success).

  1. Let request be the result of creating a potential-CORS request given url, "script", and CORS setting.

  2. Set request's client to settings object, its type to "script", its cryptographic nonce metadata to cryptographic nonce, its integrity metadata to integrity metadata and its parser metadata to parser state.

  3. If the caller specified custom steps to perform the fetch, perform them on request, with the is top-level flag set. Return from this algorithm, and when the custom perform the fetch steps complete with response response, run the remaining steps.

    Otherwise, fetch request. Return from this algorithm, and run the remaining steps as part of the fetch's process response for the response response.

    response can be either CORS-same-origin or CORS-cross-origin. This only affects how error reporting happens.

  4. Let response be response's unsafe response.

  5. If response's type is "error", or response's status is not an ok status, asynchronously complete this algorithm with null, and abort these steps.

  6. If response's Content Type metadata, if any, specifies a character encoding, and the user agent supports that encoding, then set character encoding to that encoding (ignoring the passed-in value).

  7. Let source text be the result of decoding response's body to Unicode, using character encoding as the fallback encoding.

    The decode algorithm overrides character encoding if the file contains a BOM.

  8. Let script be the result of creating a classic script using source text and settings object.

    If response was CORS-cross-origin, then pass the muted errors flag to the create a classic script algorithm as well.

  9. Asynchronously complete this algorithm with script.

To fetch a classic worker script given a url, a fetch client settings object, a destination, and a script settings object, run these steps. The algorithm will asynchronously complete with either null (on failure) or a new classic script (on success).

  1. Let request be a new request whose url is url, client is fetch client settings object, type is "script", destination is destination, mode is "same-origin", credentials mode is "same-origin", parser metadata is "not parser-inserted", and whose use-URL-credentials flag is set.

  2. If the caller specified custom steps to perform the fetch, perform them on request, with the is top-level flag set. Return from this algorithm, and when the custom perform the fetch steps complete with response response, run the remaining steps.

    Otherwise, fetch request. Return from this algorithm, and run the remaining steps as part of the fetch's process response for the response response.

  3. Let response be response's unsafe response.

  4. If response's type is "error", or response's status is not an ok status, asynchronously complete this algorithm with null, and abort these steps.

  5. Let source text be the result of UTF-8 decoding response's body.

  6. Let script be the result of creating a classic script using source text and script settings object.

  7. Asynchronously complete this algorithm with script.

To fetch a classic worker-imported script given a url and a settings object, run these steps. The algorithm will synchronously complete with a classic script on success, or throw an exception on failure.

  1. Let request be a new request whose url is url, client is settings object, type is "script", destination is "script", parser metadata is "not parser-inserted", synchronous flag is set, and whose use-URL-credentials flag is set.

  2. If the caller specified custom steps to perform the fetch, perform them on request, with the is top-level flag set. Let response be the result.

    Otherwise, fetch request, and let response be the result.

    Unlike other algorithms in this section, the fetching process is synchronous here. Thus any perform the fetch steps will also finish their work synchronously.

  3. Let response be response's unsafe response.

  4. If response's type is "error", or response's status is not an ok status, throw a "NetworkError" DOMException and abort these steps.

  5. Let source text be the result of UTF-8 decoding response's body.

  6. Let script be the result of creating a classic script using source text and settings object.

    If response was CORS-cross-origin, then pass the muted errors flag to the create a classic script algorithm as well.

  7. Return script.

To fetch a module script graph given a url, a settings object, a destination, a cryptographic nonce, a parser state, and a credentials mode, run these steps. The algorithm will asynchronously complete with either null (on failure) or a module script (on success).

  1. Perform the internal module script graph fetching procedure given url, settings object, destination, cryptographic nonce, parser state, credentials mode, settings object, a new empty list, "client", and with the top-level module fetch flag set. If the caller of this algorithm specified custom perform the fetch steps, pass those along as well.

  2. When the internal module script graph fetching procedure asynchronously completes with result, asynchronously complete this algorithm with result.

To fetch a module worker script graph given a url, a fetch client settings object, a destination, a credentials mode, and a module map settings object, run these steps. The algorithm will asynchronously complete with either null (on failure) or a module script (on success).

  1. Perform the internal module script graph fetching procedure given url, fetch client settings object, destination, the empty string, "not parser-inserted", credentials mode, module map settings object, a new empty list, "client", and with the top-level module fetch flag set. If the caller of this algorithm specified custom perform the fetch steps, pass those along as well.

  2. When the internal module script graph fetching procedure asynchronously completes with result, asynchronously complete this algorithm with result.


The following algorithms are meant for internal use by this specification only as part of fetching a module script graph or preparing a script, and should not be used directly by other specifications.

To perform the internal module script graph fetching procedure given a url, a fetch client settings object, a destination, a cryptographic nonce, a parser state, a credentials mode, a module map settings object, an ancestor list, a referrer, and a top-level module fetch flag, perform these steps. The algorithm will asynchronously complete with either null (on failure) or a module script (on success).

  1. Fetch a single module script given url, fetch client settings object, destination, cryptographic nonce, parser state, credentials mode, module map settings object, referrer, and the top-level module fetch flag. If the caller of this algorithm specified custom perform the fetch steps, pass those along while fetching a single module script.

  2. Return from this algorithm, and run the following steps when fetching a single module script asynchronously completes with result:

  3. If result is null, asynchronously complete this algorithm with null and abort these steps.

  4. Otherwise, result is a module script. Fetch the descendants of result given destination and an ancestor list obtained by appending url to ancestor list. Wait for fetching the descendants of a module script to asynchronously complete with descendants result before proceeding to the next step.

  5. Let record be result's module record.

  6. Let instantiationStatus be record.ModuleDeclarationInstantiation().

    This step will recursively call ModuleDeclarationInstantiation all of the module's uninstantiated dependencies.

  7. For each module script script in result's uninstantiated inclusive descendant module scripts, perform the following steps:

    1. If instantiationStatus is an abrupt completion, then set script's instantiation state to "errored", its instantiation error to instantiationStatus.[[Value]], and its module record to null.

    2. Otherwise, set script's instantiation state to "instantiated".

  8. Asynchronously complete this algorithm with descendants result.

    It is intentional that we complete with descendants result here, and not result, as this allows us to propagate error signals to the caller.

In the above algorithm, a module script script's uninstantiated inclusive descendant module scripts is a set of module scripts determined as follows:

  1. Let moduleMap be script's settings object's module map.

  2. Let stack be the stack « script ».

  3. Let inclusive descendants be an empty set.

  4. While stack is not empty:

    1. Let current the result of popping from stack.

    2. If inclusive descendants and stack both do not contain current, then:

      1. Append current to inclusive descendants.

      2. Let child specifiers be the value of current's module record's [[RequestedModules]] internal slot.

      3. Let child URLs be the list obtained by calling resolve a module specifier once for each item of child specifiers, given current and that item. Omit any failures.

      4. Let child modules be the list obtained by getting each value in moduleMap whose key is given by an item of child URLs.

      5. For each s in child modules that is not contained by inclusive descendants, push s onto stack.

  5. Return a set containing all items of inclusive descendants whose instantiation state is "uninstantiated".

The above algorithm gives a depth-first search of the module dependency graph. The main interesting part is in how the "edges" of this graph are determined. The actual search implementation is not important; any other technique for exploring the graph will suffice, given that the output is a set only used for membership testing and whose order is thus not important.

To fetch a single module script, given a url, a fetch client settings object, a destination, a cryptographic nonce, a parser state, a credentials mode, a module map settings object, a referrer, and a top-level module fetch flag, run these steps. The algorithm will asynchronously complete with either null (on failure) or a module script (on success).

  1. Let moduleMap be module map settings object's module map.

  2. If moduleMap[url] is "fetching", wait in parallel until that entry's value changes, then queue a task on the networking task source to proceed with running the following steps.

  3. If moduleMap[url] exists, asynchronously complete this algorithm with moduleMap[url], and abort these steps.

  4. Set moduleMap[url] to "fetching".

  5. Let request be a new request whose url is url, destination is destination, type is "script", mode is "cors", credentials mode is credentials mode, cryptographic nonce metadata is cryptographic nonce, parser metadata is parser state, referrer is referrer, and client is fetch client settings object.

  6. If the caller specified custom steps to perform the fetch, perform them on request, setting the is top-level flag if the top-level module fetch flag is set. Return from this algorithm, and when the custom perform the fetch steps complete with response response, run the remaining steps.

    Otherwise, fetch request. Return from this algorithm, and run the remaining steps as part of the fetch's process response for the response response.

    response is always CORS-same-origin.

  7. If any of the following conditions are met, set moduleMap[url] to null, asynchronously complete this algorithm with null, and abort these steps:

  8. Let source text be the result of UTF-8 decoding response's body.

  9. Let module script be the result of creating a module script given source text, module map settings object, response's url, cryptographic nonce, parser state, and credentials mode.

  10. Set moduleMap[url] to module script, and asynchronously complete this algorithm with module script.

    It is intentional that the module map is keyed by the request URL, whereas the base URL for the module script is set to the response URL. The former is used to deduplicate fetches, while the latter is used for URL resolution.

To fetch the descendants of a module script module script, given a destination and an ancestor list, run these steps. The algorithm will asynchronously complete with either null (on failure) or with module script (on success).

  1. Let record be module script's module record.

  2. If record.[[RequestedModules]] is empty, asynchronously complete this algorithm with module script.

  3. Let urls be a new empty list.

  4. For each string requested of record.[[RequestedModules]],

    1. Let url be the result of resolving a module specifier given module script and requested.

    2. If the result is error:

      1. Let error be a new TypeError exception.

      2. Report the exception error for module script.

      3. Abort this algorithm, and asynchronously complete it with null.

    3. Otherwise, if ancestor list does not contain url, append url to urls.

  5. For each url in urls, perform the internal module script graph fetching procedure given url, module script's credentials mode, module script's cryptographic nonce, module script's parser state, destination, module script's settings object, module script's settings object, ancestor list, module script's base URL, and with the top-level module fetch flag unset. If the caller of this algorithm specified custom perform the fetch steps, pass those along while performing the internal module script graph fetching procedure.

    Wait for all of the internal module script graph fetching procedure invocations to asynchronously complete. If any of them asynchronously complete with null, then asynchronously complete this algorithm with null. Otherwise, asynchronously complete this algorithm with module script.

8.1.3.3 Creating scripts

To create a classic script, given some script source, an environment settings object, and an optional muted errors flag:

  1. Let script be a new classic script that this algorithm will subsequently initialize.

  2. Set script's settings object to the environment settings object provided.

  3. If scripting is disabled for the given environment settings object's responsible browsing context, then set script's source text to the empty string. Otherwise, set script's source text to the supplied script source.

  4. If the muted errors flag was set, then set script's muted errors flag.

  5. Return script.

To create a module script, given some script source, an environment settings object, a script base URL, a cryptographic nonce, a parser state, and a credentials mode:

  1. Let script be a new module script that this algorithm will subsequently initialize.

  2. Set script's settings object to the environment settings object provided.

  3. Let realm be the provided environment settings object's Realm.

  4. If scripting is disabled for the given environment settings object's responsible browsing context, then let script source be the empty string. Otherwise, let script source be the provided script source.

  5. Let result be ParseModule(script source, realm, script).

  6. If result is a List of errors, report the exception given by the first element of result for script, return null, and abort these steps.

  7. Set script's module record to result.

  8. Set script's base URL to the script base URL provided.

  9. Set script's cryptographic nonce to the cryptographic nonce provided.

  10. Set script's parser state to the parser state.

  11. Set script's credentials mode to the credentials mode provided.

  12. Return script.

8.1.3.4 Calling scripts

To run a classic script given a classic script s and an optional rethrow errors flag:

  1. Let settings be the settings object of s.

  2. Check if we can run script with settings. If this returns "do not run", then return undefined and abort these steps.

  3. Let realm be settings's Realm.

  4. Prepare to run script with settings.

  5. Let result be ParseScript(s's source text, realm, s).

  6. If result is a List of errors, set result to the first element of result and go to the step labeled error.

  7. Let evaluationStatus be ScriptEvaluation(result).

  8. If evaluationStatus is an abrupt completion, set result to evaluationStatus.[[Value]] and go to the next step (labeled error). If evaluationStatus is a normal completion, or if ScriptEvaluation does not complete because the user agent has aborted the running script, skip to the step labeled cleanup.

  9. Error: At this point result must be an exception. Perform the following steps:

    1. If the rethrow errors flag is set and s's muted errors flag is not set, rethrow result.

    2. If the rethrow errors flag is set and s's muted errors flag is set, throw a "NetworkError" DOMException.

    3. If the rethrow errors flag is not set, report the exception given by result for the script s.

  10. Cleanup: Clean up after running script with settings.

  11. If evaluationStatus exists and is a normal completion, return evaluationStatus.[[Value]]. Otherwise, script execution was unsuccessful, either because an error occurred during parsing, or an exception occurred during evaluation, or because it was aborted prematurely.

To run a module script given a module script s:

  1. Let settings be the settings object of s.

  2. Check if we can run script with settings. If this returns "do not run" then abort these steps.

  3. If s's instantiation state is "errored", then report the exception given by s's instantiation error for s and abort these steps.

  4. Assert: s's instantiation state is "instantiated" (and thus its module record is not null).

  5. Let record be s's module record.

  6. Prepare to run script given settings.

  7. Let evaluationStatus be record.ModuleEvaluation().

    This step will recursively evaluate all of the module's dependencies.

  8. If evaluationStatus is an abrupt completion, then report the exception given by evaluationStatus.[[Value]] for s. (Do not perform this step if ModuleEvaluation fails to complete as a result of the user agent aborting the running script.)

  9. Clean up after running script with settings.

The steps to check if we can run script with an environment settings object settings are as follows. They return either "run" or "do not run".

  1. If the global object specified by settings is a Window object whose Document object is not fully active, then return "do not run" and abort these steps.

  2. If scripting is disabled for the responsible browsing context specified by settings, then return "do not run" and abort these steps.

  3. Return "run".

The steps to prepare to run script with an environment settings object settings are as follows:

  1. Increment settings's realm execution context's entrance counter by one.

  2. Push settings's realm execution context onto the JavaScript execution context stack; it is now the running JavaScript execution context.

The steps to clean up after running script with an environment settings object settings are as follows:

  1. Assert: settings's realm execution context is the running JavaScript execution context.

  2. Remove settings's realm execution context from the JavaScript execution context stack.

  3. Decrement settings's realm execution context's entrance counter by one.

  4. If the JavaScript execution context stack is now empty, perform a microtask checkpoint. (If this runs scripts, these algorithms will be invoked reentrantly.)

These algorithms are not invoked by one script directly calling another, but they can be invoked reentrantly in an indirect manner, e.g. if a script dispatches an event which has event listeners registered.

The running script is the script in the [[HostDefined]] field in the ScriptOrModule component of the running JavaScript execution context.

8.1.3.5 Realms, settings objects, and global objects

A global object is a JavaScript object that is the [[GlobalObject]] field of a JavaScript realm.

In this specification, all JavaScript realms are initialized with global objects that are either Window or WorkerGlobalScope objects.

There is always a 1-to-1-to-1 mapping between JavaScript realms, global objects, and environment settings objects:


When defining algorithm steps throughout this specification, it is often important to indicate what JavaScript realm is to be used—or, equivalently, what global object or environment settings object is to be used. In general, there are at least four possibilities:

Entry
This corresponds to the script that initiated the currently running script action: i.e., the function or script that the user agent called into when it called into author code.
Incumbent
This corresponds to the most-recently-entered author function or script on the stack, or the author function or script that originally scheduled the currently-running callback.
Current
This corresponds to the currently-running function object, including built-in user-agent functions which might not be implemented as JavaScript. (It is derived from the current JavaScript realm.)
Relevant
Every platform object has a relevant Realm, which is roughly the JavaScript realm in which it was created. When writing algorithms, the most prominent platform object whose relevant Realm might be important is the this value of the currently-running function object. In some cases, there can be other important relevant Realms, such as those of any arguments.

Note how the entry, incumbent, and current concepts are usable without qualification, whereas the relevant concept must be applied to a particular platform object.

Consider the following pages, with a.html being loaded in a browser window, b.html being loaded in an iframe as shown, and c.html and d.html omitted (they can simply be empty documents):

<!-- a.html -->
<!DOCTYPE html>
<html lang="en">
<title>Entry page</title>

<iframe src="b.html"></iframe>
<button onclick="frames[0].hello()">Hello</button>

<!--b.html -->
<!DOCTYPE html>
<html lang="en">
<title>Incumbent page</title>

<iframe src="c.html" id="c"></iframe>
<iframe src="d.html" id="d"></iframe>

<script>
  const c = document.querySelector("#c").contentWindow;
  const d = document.querySelector("#d").contentWindow;

  window.hello = () => {
    c.print.call(d);
  };
</script>

Each page has its own browsing context, and thus its own JavaScript realm, global object, and environment settings object.

When the print() method is called in response to pressing the button in a.html, then:

The incumbent and entry concepts should not be used by new specifications, as they are excessively complicated and unintuitive to work with. We are working to remove almost all existing uses from the platform: see issue #1430 for incumbent, and issue #1431 for entry.

In general, web platform specifications should use the relevant concept, applied to the object being operated on (usually the this value of the current method). This mismatches the JavaScript specification, where current is generally used as the default (e.g. in determining the JavaScript realm whose Array constructor should be used to construct the result in Array.prototype.map). But this inconsistency is so embedded in the platform that we have to accept it going forward.

Note that in constructors, where there is no this value yet, the current concept is the appropriate default.

One reason why the relevant concept is generally a better default choice than the current concept is that it is more suitable for creating an object that is to be persisted and returned multiple times. For example, the navigator.getBattery() method creates promises in the relevant Realm for the Navigator object on which it is invoked. This has the following impact: [BATTERY]

<!-- outer.html -->
<!DOCTYPE html>
<html lang="en">
<title>Relevant Realm demo: outer page</title>
<script>
  function doTest() {
    const promise = navigator.getBattery.call(frames[0].navigator);

    console.log(promise instanceof Promise);           // logs false
    console.log(promise instanceof frames[0].Promise); // logs true

    frames[0].hello();
  }
</script>
<iframe src="inner.html" onload="doTest()"></iframe>

<!-- inner.html -->
<!DOCTYPE html>
<html lang="en">
<title>Relevant Realm demo: inner page</title>
<script>
  function hello() {
    const promise = navigator.getBattery();

    console.log(promise instanceof Promise);        // logs true
    console.log(promise instanceof parent.Promise); // logs false
  }
</script>

If the algorithm for the getBattery() method had instead used the current Realm, all the results would be reversed. That is, after the first call to getBattery() in outer.html, the Navigator object in inner.html would be permanently storing a Promise object created in outer.html's JavaScript realm, and calls like that inside the hello() function would thus return a promise from the "wrong" realm. Since this is undesirable, the algorithm instead uses the relevant Realm, giving the sensible results indicated in the comments above.


The rest of this section deals with formally defining the entry, incumbent, current, and relevant concepts.

8.1.3.5.1 Entry

All realm execution contexts must contain, as part of their code evaluation state, an entrance counter value, which is initially zero. In the process of calling scripts, this value will be incremented and decremented.

With this in hand, we define the entry execution context to be the most recently pushed entry in the JavaScript execution context stack whose entrance counter value is greater than zero. The entry Realm is the entry execution context's Realm component.

Then, the entry settings object is the environment settings object of the entry Realm.

Similarly, the entry global object is the global object of the entry Realm.

8.1.3.5.2 Incumbent

All JavaScript execution contexts must contain, as part of their code evaluation state, a skip-when-determining-incumbent counter value, which is initially zero. In the process of preparing to run a callback and cleaning up after running a callback, this value will be incremented and decremented.

Every event loop has an associated backup incumbent settings object stack, initially empty. Roughly speaking, it is used to determine the incumbent settings object when no author code is on the stack, but author code is responsible for the current algorithm having been run in some way. The process of preparing to run a callback and cleaning up after running a callback manipulate this stack. [WEBIDL]

When Web IDL is used to invoke author code, or when EnqueueJob invokes a promise job, they use the following algorithms to track relevant data for determining the incumbent settings object:

To prepare to run a callback with an environment settings object settings:

  1. Push settings onto the backup incumbent settings object stack.

  2. Let context be the topmost script-having execution context.

  3. If context is not null, increment context's skip-when-determining-incumbent counter.

To clean up after running a callback with an environment settings object settings:

  1. Let context be the topmost script-having execution context.

    This will be the same as the topmost script-having execution context inside the corresponding invocation of prepare to run a callback.

  2. If context is not null, decrement context's skip-when-determining-incumbent counter.

  3. Assert: the topmost entry of the backup incumbent settings object stack is settings.

  4. Remove settings from the backup incumbent settings object stack.

Here, the topmost script-having execution context is the topmost entry of the JavaScript execution context stack that has a non-null ScriptOrModule component, or null if there is no such entry in the JavaScript execution context stack.

With all this in place, the incumbent settings object is determined as follows:

  1. Let context be the topmost script-having execution context.

  2. If context is null, or if context's skip-when-determining-incumbent counter is greater than zero, then:

    1. Assert: the backup incumbent settings object stack is not empty.

      This assert would fail if you try to obtain the incumbent settings object from inside an algorithm that was triggered neither by calling scripts nor by Web IDL invoking a callback. For example, it would trigger if you tried to obtain the incumbent settings object inside an algorithm that ran periodically as part of the event loop, with no involvement of author code. In such cases the incumbent concept cannot be used.

    2. Return the topmost entry of the backup incumbent settings object stack.

  3. Return context's Realm component's settings obect.

Then, the incumbent Realm is the Realm of the incumbent settings object.

Similarly, the incumbent global object is the global object of the incumbent settings object.


The following series of examples is intended to make it clear how all of the different mechanisms contribute to the definition of the incumbent concept:

Consider the following very simple example:

<!DOCTYPE html>
<iframe></iframe>
<script>
  new frames[0].MessageChannel();
</script>

When the MessageChannel() constructor looks up the incumbent settings object to use as the owner of the new MessagePort objects, the topmost script-having execution context will be that corresponding to the script element: it was pushed onto the JavaScript execution context stack as part of ScriptEvaluation during the run a classic script algorithm. Since there are no Web IDL callback invocations involved, the context's skip-when-determining-incumbent counter is zero, so it is used to determine the incumbent settings object; the result is the environment settings object of window.

(In this example, the environment settings object of frames[0] is not involved at all. It is the current settings object, but the MessageChannel() constructor cares only about the incumbent, not current.)

Consider the following more complicated example:

<!DOCTYPE html>
<iframe></iframe>
<script>
  const bound = frames[0].postMessage.bind(frames[0], "some data", "*");
  window.setTimeout(bound);
</script>

There are two interesting environment settings objects here: that of window, and that of frames[0]. Our concern is: what is the incumbent settings object at the time that the algorithm for postMessage() executes?

It should be that of window, to capture the intuitive notion that the author script responsible for causing the algorithm to happen is executing in window, not frames[0]. Another way of capturing the intuition here is that invoking algorithms asynchronously (in this case via setTimeout()) should not change the incumbent concept.

Let us now explain how the steps given above give us our intuitively-desired result of window's relevant settings object.

When bound is converted to a Web IDL callback type, the incumbent settings object is that corresponding to window (in the same manner as in our simple example above). Web IDL stores this as the resulting callback value's callback context.

When the task posted by setTimeout() executes, the algorithm for that task uses Web IDL to invoke the stored callback value. Web IDL in turn calls the above prepare to run a callback algorithm. This pushes the stored callback context onto the backup incumbent settings object stack. At this time (inside the timer task) there is no author code on the stack, so the topmost script-having execution context is null, and nothing gets its skip-when-determining-incumbent counter incremented.

Invoking the callback then calls bound, which in turn calls the postMessage() method of frames[0]. When the postMessage() algorithm looks up the incumbent settings object, there is still no author code on the stack, since the bound function just directly calls the built-in method. So the topmost script-having execution context will be null: the JavaScript execution context stack only contains an execution context corresponding to postMessage(), with no ScriptEvaluation context or similar below it.

This is where we fall back to the backup incumbent settings object stack. As noted above, it will contain as its topmost entry the relevant settings object of window. So that is what is used as the incumbent settings object while executing the postMessage() algorithm.

Consider this final, even more convoluted example:

<!-- a.html -->
<!DOCTYPE html>
<button>click me</button>
<iframe></iframe>
<script>
const bound = frames[0].location.assign.bind(frames[0].location, "https://example.com/");
document.querySelector("button").addEventListener("click", bound);
</script>

<!-- b.html -->
<!DOCTYPE html>
<iframe src="a.html"></iframe>
<script>
  const iframe = document.querySelector("iframe");
  iframe.onload = function onLoad() {
    iframe.contentWindow.document.querySelector("button").click();
  };
</script>

Again there are two interesting environment settings objects in play: that of a.html, and that of b.html. When the location.assign() method triggers the Location-object navigate algorithm, what will be the incumbent settings object? As before, it should intuitively be that of a.html: the click listener was originally scheduled by a.html, so even if something involving b.html causes the listener to fire, the incumbent responsible is that of a.html.

The callback setup is similar to the previous example: when bound is converted to a Web IDL callback type, the incumbent settings object is that corresponding to a.html, which is stored as the callback's callback context.

When the click() method is called inside b.html, it dispatches a click event on the button that is inside a.html. This time, when the prepare to run a callback algorithm executes as part of event dispatch, there is author code on the stack; the topmost script-having execution context is that of the onLoad function, whose skip-when-determining-incumbent counter gets incremented. Additionally, a.html's environment settings object (stored as the EventHandler's callback context) is pushed onto the backup incumbent settings object stack.

Now, when the Location-object navigate algorithm looks up the incumbent settings object, the topmost script-having execution context is still that of the onLoad function (due to the fact we are using a bound function as the callback). Its skip-when-determining-incumbent counter value is one, however, so we fall back to the backup incumbent settings object stack. This gives us the environment settings object of a.html, as expected.

Note that this means that even though it is the iframe inside a.html that navigates, it is a.html itself that is used as the source browsing context, which determines among other things the request client. This is perhaps the only justifiable use of the incumbent concept on the web platform; in all other cases the consequences of using it are simply confusing and we hope to one day switch them to use current or relevant as appropriate.

8.1.3.5.3 Current

The JavaScript specification defines the current Realm Record, sometimes abbreviated to the "current Realm". [JAVASCRIPT]

Then, the current settings object is the environment settings object of the current Realm Record.

Similarly, the current global object is the global object of the current Realm Record.

8.1.3.5.4 Relevant

The relevant settings object for a platform object is defined as follows:

If the object is a global object
Each global object in this specification is created alongside a corresponding environment settings object; that is its relevant settings object.
Otherwise

The relevant settings object for a non-global platform object o is the environment settings object whose global object is the global object of the global environment associated with o.

The "global environment associated with" concept is from the olden days, before the modern JavaScript specification and its concept of realms. We expect that as the Web IDL specification gets updated, every platform object will have a Realm associated with it, and this definition can be re-cast in those terms. [JAVASCRIPT] [WEBIDL]

Then, the relevant Realm for a platform object is the Realm of its relevant settings object.

Similarly, the relevant global object for a platform object is the global object of its relevant settings object.

8.1.3.6 Killing scripts

Although the JavaScript specification does not account for this possibility, it's sometimes necessary to abort a running script. This causes any ScriptEvaluation or ModuleEvaluation to cease immediately, emptying the JavaScript execution context stack without triggering any of the normal mechanisms like finally blocks. [JAVASCRIPT]

User agents may impose resource limitations on scripts, for example CPU quotas, memory limits, total execution time limits, or bandwidth limitations. When a script exceeds a limit, the user agent may either throw a "QuotaExceededError" DOMException, abort the script without an exception, prompt the user, or throttle script execution.

For example, the following script never terminates. A user agent could, after waiting for a few seconds, prompt the user to either terminate the script or let it continue.

<script>
 while (true) { /* loop */ }
</script>

User agents are encouraged to allow users to disable scripting whenever the user is prompted either by a script (e.g. using the window.alert() API) or because of a script's actions (e.g. because it has exceeded a time limit).

If scripting is disabled while a script is executing, the script should be terminated immediately.

User agents may allow users to specifically disable scripts just for the purposes of closing a browsing context.

For example, the prompt mentioned in the example above could also offer the user with a mechanism to just close the page entirely, without running any unload event handlers.

8.1.3.7 Integration with the JavaScript job queue

The JavaScript specification defines the JavaScript job and job queue abstractions in order to specify certain invariants about how promise operations execute with a clean JavaScript execution context stack and in a certain order. However, as of the time of this writing the definition of EnqueueJob in that specification is not sufficiently flexible to integrate with HTML as a host environment. [JAVASCRIPT]

This is not strictly true. It is in fact possible, by taking liberal advantage of the many "implementation defined" sections of the algorithm, to contort it to our purposes. However, the end result is a mass of messy indirection and workarounds that essentially bypasses the job queue infrastructure entirely, albeit in a way that is technically sanctioned within the bounds of implementation-defined behavior. We do not take this path, and instead introduce the following willful violation.

As such, user agents must instead use the following definition in place of that in the JavaScript specification. These ensure that the promise jobs enqueued by the JavaScript specification are properly integrated into the user agent's event loops.

The RunJobs abstract operation from the JavaScript specification must not be used by user agents.

8.1.3.7.1 EnqueueJob(queueName, job, arguments)

When the JavaScript specification says to call the EnqueueJob abstract operation, the following algorithm must be used in place of JavaScript's EnqueueJob:

  1. Assert: queueName is "PromiseJobs". ("ScriptJobs" must not be used by user agents.)

  2. Let job settings be some appropriate environment settings object.

    It is not yet clear how to specify the environment settings object that should be used here. In practice, this means that the entry concept is not correctly specified while executing a job. See discussion in issue #1189.

  3. Let incumbent settings be the incumbent settings object.

  4. Queue a microtask, on job settings's responsible event loop, to perform the following steps:

    1. Check if we can run script with job settings. If this returns "do not run" then abort these steps.

    2. Prepare to run script with job settings.

    3. Prepare to run a callback with incumbent settings.

    4. Let result be the result of performing the abstract operation specified by job, using the elements of arguments as its arguments.

    5. Clean up after running a callback with incumbent settings.

    6. Clean up after running script with job settings.

    7. If result is an abrupt completion, report the exception given by result.[[Value]].

8.1.3.8 Integration with the JavaScript module system

The JavaScript specification defines a syntax for modules, as well as some host-agnostic parts of their processing model. This specification defines the rest of their processing model: how the module system is bootstrapped, via the script element with type attribute set to "module", and how modules are fetched, resolved, and executed. [JAVASCRIPT]

Although the JavaScript specification speaks in terms of "scripts" versus "modules", in general this specification speaks in terms of classic scripts versus module scripts, since both of them use the script element.

A module map is a map of absolute URLs to values that are either a module script, null (used to represent failed fetches), or a placeholder value "fetching". Module maps are used to ensure that imported JavaScript modules are only fetched, parsed, and evaluated once per Document or worker.

Since module maps are keyed by URL, the following code will create three separate entries in the module map, since it results in three different URLs:

import "https://example.com/module.js";
import "https://example.com/module.js#map-buster";
import "https://example.com/module.js?debug=true";

That is, URL queries and fragments can be varied to create distinct entries in the module map; they are not ignored. Thus, three separate fetches and three separate module evaluations will be performed.

In contrast, the following code would only create a single entry in the module map, since after applying the URL parser to these inputs, the resulting URL records are equal:

import "https://example.com/module2.js";
import "https:example.com/module2.js";
import "https://///example.com\\module2.js";
import "https://example.com/foo/../module2.js";

So in this second example, only one fetch and one module evaluation will occur.

Note that this behavior is the same as how shared workers are keyed by their parsed constructor url.

To resolve a module specifier given a module script script and a string specifier, perform the following steps. It will return either an absolute URL or failure.

  1. Apply the URL parser to specifier. If the result is not failure, return the result.

  2. If specifier does not start with the character U+002F SOLIDUS (/), the two-character sequence U+002E FULL STOP, U+002F SOLIDUS (./), or the three-character sequence U+002E FULL STOP, U+002E FULL STOP, U+002F SOLIDUS (../), return failure and abort these steps.

    This restriction is in place so that in the future we can allow custom module loaders to give special meaning to "bare" import specifiers, like import "jquery" or import "web/crypto". For now any such imports will fail, instead of being treated as relative URLs.

  3. Return the result of applying the URL parser to specifier with script's base URL as the base URL.

The following are valid module specifiers according to the above algorithm:

The following are valid module specifiers according to the above algorithm, but will invariably cause failures when they are fetched:

The following are not valid module specifiers according to the above algorithm:

8.1.3.8.1 HostResolveImportedModule(referencingModule, specifier)

JavaScript contains an implementation-defined HostResolveImportedModule abstract operation. User agents must use the following implementation: [JAVASCRIPT]

  1. Let referencing module script be referencingModule.[[HostDefined]].

  2. Let moduleMap be referencing module script's settings object's module map.

  3. Let url be the result of resolving a module specifier given referencing module script and specifier. If the result is failure, then throw a TypeError exception and abort these steps.

  4. Let resolved module script be moduleMap[url]. If no such entry exists, or if resolved module script is null or "fetching", then throw a TypeError exception and abort these steps.

  5. If resolved module script's instantiation state is "errored", then throw resolved module script's instantiation error.

  6. Assert: resolved module script's instantiation state is "instantiated" (and thus its module record is not null).

  7. Return resolved module script's module record.

8.1.3.9 Runtime script errors

When the user agent is required to report an error for a particular script script with a particular position line:col, using a particular target target, it must run these steps, after which the error is either handled or not handled:

  1. If target is in error reporting mode, then abort these steps; the error is not handled.

  2. Let target be in error reporting mode.

  3. Let message be a user-agent-defined string describing the error in a helpful manner. (This is a fingerprinting vector.)

  4. Let errorValue be the value that represents the error: in the case of an uncaught exception, that would be the value that was thrown; in the case of a JavaScript error that would be an Error object. If there is no corresponding value, then the null value must be used instead.

  5. Let urlString be the result of applying the URL serializer to the URL record that corresponds to the resource from which script was obtained.

    The resource containing the script will typically be the file from which the Document was parsed, e.g. for inline script elements or event handler content attributes; or the JavaScript file that the script was in, for external scripts. Even for dynamically-generated scripts, user agents are strongly encouraged to attempt to keep track of the original source of a script. For example, if an external script uses the document.write() API to insert an inline script element during parsing, the URL of the resource containing the script would ideally be reported as being the external script, and the line number might ideally be reported as the line with the document.write() call or where the string passed to that call was first constructed. Naturally, implementing this can be somewhat non-trivial.

    User agents are similarly encouraged to keep careful track of the original line numbers, even in the face of document.write() calls mutating the document as it is parsed, or event handler content attributes spanning multiple lines.

  6. If script has muted errors, then set message to "Script error.", urlString to the empty string, line and col to 0, and errorValue to null.

  7. Let notHandled be the result of firing an event named error at target, using ErrorEvent, with the cancelable attribute initialized to true, the message attribute initialized to message, the filename attribute initialized to urlString, the lineno attribute initialized to line, the colno attribute initialized to col, and the error attribute initialized to errorValue.

  8. Let target no longer be in error reporting mode.

  9. If notHandled is false, then the error is handled. Otherwise, the error is not handled.

    Returning true in an event handler cancels the event per the event handler processing algorithm.

8.1.3.9.1 Runtime script errors in documents

When the user agent is to report an exception E, the user agent must report the error for the relevant script, with the problematic position (line number and column number) in the resource containing the script, using the global object specified by the script's settings object as the target. If the error is still not handled after this, then the error may be reported to a developer console.

8.1.3.9.2 The ErrorEvent interface
[Constructor(DOMString type, optional ErrorEventInit eventInitDict), Exposed=(Window,Worker)]
interface ErrorEvent : Event {
  readonly attribute DOMString message;
  readonly attribute USVString filename;
  readonly attribute unsigned long lineno;
  readonly attribute unsigned long colno;
  readonly attribute any error;
};

dictionary ErrorEventInit : EventInit {
  DOMString message = "";
  USVString filename = "";
  unsigned long lineno = 0;
  unsigned long colno = 0;
  any error = null;
};

The message attribute must return the value it was initialized to. It represents the error message.

The filename attribute must return the value it was initialized to. It represents the URL of the script in which the error originally occurred.

The lineno attribute must return the value it was initialized to. It represents the line number where the error occurred in the script.

The colno attribute must return the value it was initialized to. It represents the column number where the error occurred in the script.

The error attribute must return the value it was initialized to. Where appropriate, it is set to the object representing the error (e.g., the exception object in the case of an uncaught DOM exception).

8.1.3.10 Unhandled promise rejections

In addition to synchronous runtime script errors, scripts may experience asynchronous promise rejections, tracked via the unhandledrejection and rejectionhandled events.

When the user agent is to notify about rejected promises on a given environment settings object settings object, it must run these steps:

  1. Let list be a copy of settings object's about-to-be-notified rejected promises list.

  2. If list is empty, abort these steps.

  3. Clear settings object's about-to-be-notified rejected promises list.

  4. Queue a task to run the following substep:

    1. For each promise p in list:

      1. If p's [[PromiseIsHandled]] internal slot is true, continue to the next iteration of the loop.

      2. Let notHandled be the result of firing an event named unhandledrejection at settings object's global object, using PromiseRejectionEvent, with the cancelable attribute initialized to true, the promise attribute initialized to p, and the reason attribute initialized to the value of p's [[PromiseResult]] internal slot.

      3. If notHandled is false, then the promise rejection is handled. Otherwise, the promise rejection is not handled.

      4. If p's [[PromiseIsHandled]] internal slot is false, add p to settings object's outstanding rejected promises weak set.

This algorithm results in promise rejections being marked as handled or not handled. These concepts parallel handled and not handled script errors. If a rejection is still not handled after this, then the rejection may be reported to a developer console.

8.1.3.10.1 HostPromiseRejectionTracker(promise, operation)

JavaScript contains an implementation-defined HostPromiseRejectionTracker(promise, operation) abstract operation. User agents must use the following implementation: [JAVASCRIPT]

  1. Let script be the running script.

  2. If script has muted errors, terminate these steps.

  3. Let settings object be script's settings object.

  4. If operation is "reject",

    1. Add promise to settings object's about-to-be-notified rejected promises list.

  5. If operation is "handle",

    1. If settings object's about-to-be-notified rejected promises list contains promise, remove promise from that list and abort these steps.

    2. If settings object's outstanding rejected promises weak set does not contain promise, abort these steps.

    3. Remove promise from settings object's outstanding rejected promises weak set.

    4. Queue a task to fire an event named rejectionhandled at settings object's global object, using PromiseRejectionEvent, with the promise attribute initialized to promise, and the reason attribute initialized to the value of promise's [[PromiseResult]] internal slot.

8.1.3.10.2 The PromiseRejectionEvent interface
[Constructor(DOMString type, PromiseRejectionEventInit eventInitDict), Exposed=(Window,Worker)]
interface PromiseRejectionEvent : Event {
  readonly attribute Promise<any> promise;
  readonly attribute any reason;
};

dictionary PromiseRejectionEventInit : EventInit {
  required Promise<any> promise;
  any reason;
};

The promise attribute must return the value it was initialized to. It represents the promise which this notification is about.

The reason attribute must return the value it was initialized to. It represents the rejection reason for the promise.

8.1.3.11 HostEnsureCanCompileStrings(callerRealm, calleeRealm)

JavaScript contains an implementation-defined HostEnsureCanCompileStrings(callerRealm, calleeRealm) abstract operation. User agents must use the following implementation: [JAVASCRIPT]

  1. Perform ? EnsureCSPDoesNotBlockStringCompilation(callerRealm, calleeRealm). [CSP]

8.1.4 Event loops

8.1.4.1 Definitions

To coordinate events, user interaction, scripts, rendering, networking, and so forth, user agents must use event loops as described in this section. There are two kinds of event loops: those for browsing contexts, and those for workers.

There must be at least one browsing context event loop per user agent, and at most one per unit of related similar-origin browsing contexts.

When there is more than one event loop for a unit of related browsing contexts, complications arise when a browsing context in that group is navigated such that it switches from one unit of related similar-origin browsing contexts to another. This specification does not currently describe how to handle these complications.

A browsing context event loop always has at least one browsing context. If such an event loop's browsing contexts all go away, then the event loop goes away as well. A browsing context always has an event loop coordinating its activities.

Worker event loops are simpler: each worker has one event loop, and the worker processing model manages the event loop's lifetime.


An event loop has one or more task queues. A task queue is an ordered list of tasks, which are algorithms that are responsible for such work as:

Events

Dispatching an Event object at a particular EventTarget object is often done by a dedicated task.

Not all events are dispatched using the task queue, many are dispatched during other tasks.

Parsing

The HTML parser tokenizing one or more bytes, and then processing any resulting tokens, is typically a task.

Callbacks

Calling a callback is often done by a dedicated task.

Using a resource

When an algorithm fetches a resource, if the fetching occurs in a non-blocking fashion then the processing of the resource once some or all of the resource is available is performed by a task.

Reacting to DOM manipulation

Some elements have tasks that trigger in response to DOM manipulation, e.g. when that element is inserted into the document.

Each task in a browsing context event loop is associated with a Document; if the task was queued in the context of an element, then it is the element's node document; if the task was queued in the context of a browsing context, then it is the browsing context's active document at the time the task was queued; if the task was queued by or for a script then the document is the responsible document specified by the script's settings object.

A task is intended for a specific event loop: the event loop that is handling tasks for the task's associated Document or worker.

When a user agent is to queue a task, it must add the given task to one of the task queues of the relevant event loop.

Each task is defined as coming from a specific task source. All the tasks from one particular task source and destined to a particular event loop (e.g. the callbacks generated by timers of a Document, the events fired for mouse movements over that Document, the tasks queued for the parser of that Document) must always be added to the same task queue, but tasks from different task sources may be placed in different task queues.

For example, a user agent could have one task queue for mouse and key events (the user interaction task source), and another for everything else. The user agent could then give keyboard and mouse events preference over other tasks three quarters of the time, keeping the interface responsive but not starving other task queues, and never processing events from any one task source out of order.

Each event loop has a currently running task. Initially, this is null. It is used to handle reentrancy. Each event loop also has a performing a microtask checkpoint flag, which must initially be false. It is used to prevent reentrant invocation of the perform a microtask checkpoint algorithm.

8.1.4.2 Processing model

An event loop must continually run through the following steps for as long as it exists:

  1. Select the oldest task on one of the event loop's task queues, if any, ignoring, in the case of a browsing context event loop, tasks whose associated Documents are not fully active. The user agent may pick any task queue. If there is no task to select, then jump to the microtasks step below.

  2. Set the event loop's currently running task to the task selected in the previous step.

  3. Run: Run the selected task.

  4. Set the event loop's currently running task back to null.

  5. Remove the task that was run in the run step above from its task queue.

  6. Microtasks: Perform a microtask checkpoint.

  7. Update the rendering: If this event loop is a browsing context event loop (as opposed to a worker event loop), then run the following substeps.

    1. Let now be the value that would be returned by the Performance object's now() method. [HRT]

    2. Let docs be the list of Document objects associated with the event loop in question, sorted arbitrarily except that the following conditions must be met:

      In the steps below that iterate over docs, each Document must be processed in the order it is found in the list.

    3. If there are top-level browsing contexts B that the user agent believes would not benefit from having their rendering updated at this time, then remove from docs all Document objects whose browsing context's top-level browsing context is in B.

      Whether a top-level browsing context would benefit from having its rendering updated depends on various factors, such as the update frequency. For example, if the browser is attempting to achieve a 60Hz refresh rate, then these steps are only necessary every 60th of a second (about 16.7ms). If the browser finds that a top-level browsing context is not able to sustain this rate, it might drop to a more sustainable 30Hz for that set of Documents, rather than occasionally dropping frames. (This specification does not mandate any particular model for when to update the rendering.) Similarly, if a top-level browsing context is in the background, the user agent might decide to drop that page to a much slower 4Hz, or even less.

      Another example of why a browser might skip updating the rendering is to ensure certain tasks are executed immediately after each other, with only microtask checkpoints interleaved (and without, e.g., animation frame callbacks interleaved). For example, a user agent might wish to coalesce timer callbacks together, with no intermediate rendering updates.

    4. If there are a nested browsing contexts B that the user agent believes would not benefit from having their rendering updated at this time, then remove from docs all Document objects whose browsing context is in B.

      As with top-level browsing contexts, a variety of factors can influence whether it is profitable for a browser to update the rendering of nested browsing contexts. For example, a user agent might wish to spend less resources rendering third-party content, especially if it is not currently visible to the user or if resources are constrained. In such cases, the browser could decide to update the rendering for such content infrequently or never.

    5. For each fully active Document in docs, run the resize steps for that Document, passing in now as the timestamp. [CSSOMVIEW]

    6. For each fully active Document in docs, run the scroll steps for that Document, passing in now as the timestamp. [CSSOMVIEW]

    7. For each fully active Document in docs, evaluate media queries and report changes for that Document, passing in now as the timestamp. [CSSOMVIEW]

    8. For each fully active Document in docs, run CSS animations and send events for that Document, passing in now as the timestamp. [CSSANIMATIONS]

    9. For each fully active Document in docs, run the fullscreen rendering steps for that Document, passing in now as the timestamp. [FULLSCREEN]

      Spec bugs: 28001

    10. For each fully active Document in docs, run the animation frame callbacks for that Document, passing in now as the timestamp.

    11. For each fully active Document in docs, run the update intersection observations steps for that Document, passing in now as the timestamp. [INTERSECTIONOBSERVER]

    12. For each fully active Document in docs, update the rendering or user interface of that Document and its browsing context to reflect the current state.

  8. If this is a worker event loop (i.e. one running for a WorkerGlobalScope), but there are no tasks in the event loop's task queues and the WorkerGlobalScope object's closing flag is true, then destroy the event loop, aborting these steps, resuming the run a worker steps described in the Web workers section below.

  9. Return to the first step of the event loop.


Each event loop has a microtask queue. A microtask is a task that is originally to be queued on the microtask queue rather than a task queue. There are two kinds of microtasks: solitary callback microtasks, and compound microtasks.

This specification only has solitary callback microtasks. Specifications that use compound microtasks have to take extra care to wrap callbacks to handle spinning the event loop.

When an algorithm requires a microtask to be queued, it must be appended to the relevant event loop's microtask queue; the task source of such a microtask is the microtask task source.

It is possible for a microtask to be moved to a regular task queue, if, during its initial execution, it spins the event loop. In that case, the microtask task source is the task source used. Normally, the task source of a microtask is irrelevant.

When a user agent is to perform a microtask checkpoint, if the performing a microtask checkpoint flag is false, then the user agent must run the following steps:

  1. Let the performing a microtask checkpoint flag be true.

  2. Microtask queue handling: If the event loop's microtask queue is empty, jump to the done step below.

  3. Select the oldest microtask on the event loop's microtask queue.

  4. Set the event loop's currently running task to the task selected in the previous step.

  5. Run: Run the selected task.

    This might involve invoking scripted callbacks, which eventually calls the clean up after running script steps, which call this perform a microtask checkpoint algorithm again, which is why we use the performing a microtask checkpoint flag to avoid reentrancy.

  6. Set the event loop's currently running task back to null.

  7. Remove the microtask run in the step above from the microtask queue, and return to the microtask queue handling step.

  8. Done: For each environment settings object whose responsible event loop is this event loop, notify about rejected promises on that environment settings object.

  9. Cleanup Indexed Database transactions.

  10. Let the performing a microtask checkpoint flag be false.

If, while a compound microtask is running, the user agent is required to execute a compound microtask subtask to run a series of steps, the user agent must run the following steps:

  1. Let parent be the event loop's currently running task (the currently running compound microtask).

  2. Let subtask be a new task that consists of running the given series of steps. The task source of such a microtask is the microtask task source. This is a compound microtask subtask.

  3. Set the event loop's currently running task to subtask.

  4. Run subtask.

  5. Set the event loop's currently running task back to parent.


When an algorithm running in parallel is to await a stable state, the user agent must queue a microtask that runs the following steps, and must then stop executing (execution of the algorithm resumes when the microtask is run, as described in the following steps):

  1. Run the algorithm's synchronous section.

  2. Resumes execution of the algorithm in parallel, if appropriate, as described in the algorithm's steps.

Steps in synchronous sections are marked with ⌛.


When an algorithm says to spin the event loop until a condition goal is met, the user agent must run the following steps:

  1. Let task be the event loop's currently running task.

    This might be a microtask, in which case it is a solitary callback microtask. It could also be a compound microtask subtask, or a regular task that is not a microtask. It will not be a compound microtask.

  2. Let task source be task's task source.

  3. Let old stack be a copy of the JavaScript execution context stack.

  4. Empty the JavaScript execution context stack.

  5. Perform a microtask checkpoint.

  6. Stop task, allowing whatever algorithm that invoked it to resume, but continue these steps in parallel.

    This causes one of the following algorithms to continue: the event loop's main set of steps, the perform a microtask checkpoint algorithm, or the execute a compound microtask subtask algorithm.

  7. Wait until the condition goal is met.

  8. Queue a task to continue running these steps, using the task source task source. Wait until this new task runs before continuing these steps.

  9. Replace the JavaScript execution context stack with the old stack.

  10. Return to the caller.


Some of the algorithms in this specification, for historical reasons, require the user agent to pause while running a task until a condition goal is met. This means running the following steps:

  1. If necessary, update the rendering or user interface of any Document or browsing context to reflect the current state.

  2. Wait until the condition goal is met. While a user agent has a paused task, the corresponding event loop must not run further tasks, and any script in the currently running task must block. User agents should remain responsive to user input while paused, however, albeit in a reduced capacity since the event loop will not be doing anything.

Pausing is highly detrimental to the user experience, especially in scenarios where a single event loop is shared among multiple documents. User agents are encouraged to experiment with alternatives to pausing, such as spinning the event loop or even simply proceeding without any kind of suspended execution at all, insofar as it is possible to do so while preserving compatibility with existing content. This specification will happily change if a less-drastic alternative is discovered to be web-compatible.

In the interim, implementers should be aware that the variety of alternatives that user agents might experiment with can change subtle aspects of event loop behavior, including task and microtask timing. Implementations should continue experimenting even if doing so causes them to violate the exact semantics implied by the pause operation.

8.1.4.3 Generic task sources

The following task sources are used by a number of mostly unrelated features in this and other specifications.

The DOM manipulation task source

This task source is used for features that react to DOM manipulations, such as things that happen in a non-blocking fashion when an element is inserted into the document.

The user interaction task source

This task source is used for features that react to user interaction, for example keyboard or mouse input.

Events sent in response to user input (e.g. click events) must be fired using tasks queued with the user interaction task source. [UIEVENTS]

The networking task source

This task source is used for features that trigger in response to network activity.

The history traversal task source

This task source is used to queue calls to history.back() and similar APIs.

8.1.5 Events

8.1.5.1 Event handlers

Many objects can have event handlers specified. These act as non-capture event listeners for the object on which they are specified. [DOM]

An event handler has a name, which always starts with "on" and is followed by the name of the event for which it is intended.

An event handler has a value, which is either null, or is a callback object, or is an internal raw uncompiled handler. The EventHandler callback function type describes how this is exposed to scripts. Initially, an event handler's value must be set to null.

Event handlers are exposed in one of two ways.

The first way, common to all event handlers, is as an event handler IDL attribute.

The second way is as an event handler content attribute. Event handlers on HTML elements and some of the event handlers on Window objects are exposed in this way.


An event handler IDL attribute is an IDL attribute for a specific event handler. The name of the IDL attribute is the same as the name of the event handler.

Event handler IDL attributes, on setting, must set the corresponding event handler to their new value, and on getting, must return the result of getting the current value of the event handler in question.

If an event handler IDL attribute exposes an event handler of an object that doesn't exist, it must always return null on getting and must do nothing on setting.

This can happen in particular for event handler IDL attribute on body elements that do not have corresponding Window objects.

Certain event handler IDL attributes have additional requirements, in particular the onmessage attribute of MessagePort objects.


An event handler content attribute is a content attribute for a specific event handler. The name of the content attribute is the same as the name of the event handler.

Event handler content attributes, when specified, must contain valid JavaScript code which, when parsed, would match the FunctionBody production after automatic semicolon insertion.

When an event handler content attribute is set, execute the following steps:

  1. If the Should element's inline behavior be blocked by Content Security Policy? algorithm returns "Blocked" when executed upon the attribute's element, "script attribute", and the attribute's value, then abort these steps. [CSP]

  2. Set the corresponding event handler to an internal raw uncompiled handler consisting of the attribute's new value and the script location where the attribute was set to this value

When an event handler content attribute is removed, the user agent must set the corresponding event handler to null.


When an event handler H of an element or object T implementing the EventTarget interface is first set to a non-null value, the user agent must append an event listener to the list of event listeners associated with T with type set to the event handler event type corresponding to H and callback set to the result of creating a Web IDL EventListener instance representing a reference to a function of one argument that executes the steps of the event handler processing algorithm, given H and its argument. The EventListener's callback context can be arbitrary; it does not impact the steps of the event handler processing algorithm. [DOM]

The callback is emphatically not the event handler itself. Every event handler ends up registering the same callback, the algorithm defined below, which takes care of invoking the right callback, and processing the callback's return value.

This only happens the first time the event handler's value is set. Since listeners are called in the order they were registered, the order of event listeners for a particular event type will always be first the event listeners registered with addEventListener() before the first time the event handler was set to a non-null value, then the callback to which it is currently set, if any, and finally the event listeners registered with addEventListener() after the first time the event handler was set to a non-null value.

This example demonstrates the order in which event listeners are invoked. If the button in this example is clicked by the user, the page will show four alerts, with the text "ONE", "TWO", "THREE", and "FOUR" respectively.

<button id="test">Start Demo</button>
<script>
 var button = document.getElementById('test');
 button.addEventListener('click', function () { alert('ONE') }, false);
 button.setAttribute('onclick', "alert('NOT CALLED')"); // event handler listener is registered here
 button.addEventListener('click', function () { alert('THREE') }, false);
 button.onclick = function () { alert('TWO'); };
 button.addEventListener('click', function () { alert('FOUR') }, false);
</script>

The interfaces implemented by the event object do not influence whether an event handler is triggered or not.

The event handler processing algorithm for an event handler H and an Event object E is as follows:

  1. Let callback be the result of getting the current value of the event handler H.

  2. If callback is null, then abort these steps.

  3. Process the Event object E as follows:

    If E is an ErrorEvent object and the event handler IDL attribute's type is OnErrorEventHandler

    Invoke callback with five arguments, the first one having the value of E's message attribute, the second having the value of E's filename attribute, the third having the value of E's lineno attribute, the fourth having the value of E's colno attribute, the fifth having the value of E's error attribute, and with the callback this value set to E's currentTarget. Let return value be the callback's return value. [WEBIDL]

    Otherwise

    Invoke callback with one argument, the value of which is the Event object E, with the callback this value set to E's currentTarget. Let return value be the callback's return value. [WEBIDL]

    In this step, invoke means to invoke the Web IDL callback function.

    If an exception gets thrown by the callback, end these steps and allow the exception to propagate. (It will propagate to the DOM event dispatch logic, which will then report the exception.)

  4. Process return value as follows:

    If E's type is mouseover
    If E's type is error and E is an ErrorEvent object

    If return value is true, then set E's canceled flag.

    If E's type is beforeunload and E is a BeforeUnloadEvent object

    The event handler IDL attribute's type is OnBeforeUnloadEventHandler, and the return value will therefore have been coerced into either the value null or a DOMString.

    If return value is not null, then:

    1. Set E's canceled flag.

    2. If E's returnValue attribute's value is the empty string, then set E's returnValue attribute's value to return value.

    Otherwise

    If return value is false, then set E's canceled flag.


The EventHandler callback function type represents a callback used for event handlers. It is represented in Web IDL as follows:

[TreatNonObjectAsNull]
callback EventHandlerNonNull = any (Event event);
typedef EventHandlerNonNull? EventHandler;

In JavaScript, any Function object implements this interface.

For example, the following document fragment:

<body onload="alert(this)" onclick="alert(this)">

...leads to an alert saying "[object Window]" when the document is loaded, and an alert saying "[object HTMLBodyElement]" whenever the user clicks something in the page.

The return value of the function affects whether the event is canceled or not: as described above, if the return value is false, the event is canceled (except for mouseover events, where the return value has to be true to cancel the event). With beforeunload events, the value is instead used to determine whether or not to prompt about unloading the document.

For historical reasons, the onerror handler has different arguments:

[TreatNonObjectAsNull]
callback OnErrorEventHandlerNonNull = any ((Event or DOMString) event, optional DOMString source, optional unsigned long lineno, optional unsigned long colno, optional any error);
typedef OnErrorEventHandlerNonNull? OnErrorEventHandler;

Similarly, the onbeforeunload handler has a different return value:

[TreatNonObjectAsNull]
callback OnBeforeUnloadEventHandlerNonNull = DOMString? (Event event);
typedef OnBeforeUnloadEventHandlerNonNull? OnBeforeUnloadEventHandler;

An internal raw uncompiled handler is a tuple with the following information:

When the user agent is to get the current value of the event handler H, it must run these steps:

  1. If H's value is an internal raw uncompiled handler, run these substeps:

    1. If H is an element's event handler, then let element be the element, and document be the element's node document.

      Otherwise, H is a Window object's event handler: let element be null, and let document be H's associated Document.

    2. If scripting is disabled for document, then return null.

    3. Let body be the uncompiled script body in the internal raw uncompiled handler.

    4. Let location be the location where the script body originated, as given by the internal raw uncompiled handler.

    5. If element is not null and element has a form owner, let form owner be that form owner. Otherwise, let form owner be null.

    6. Let settings object be the relevant settings object of document.

    7. If body is not parsable as FunctionBody or if parsing detects an early error, then follow these substeps:

      1. Set H's value to null.

      2. Report the error for the appropriate script and with the appropriate position (line number and column number) given by location, using settings object's global object. If the error is still not handled after this, then the error may be reported to a developer console.

      3. Return null.

    8. If body begins with a Directive Prologue that contains a Use Strict Directive then let strict be true, otherwise let strict be false.

    9. Push settings object's realm execution context onto the JavaScript execution context stack; it is now the running JavaScript execution context.

      This is necessary so the subsequent invocation of FunctionCreate takes place in the correct JavaScript Realm.

    10. Let function be the result of calling FunctionCreate, with arguments:

      kind
      Normal
      ParameterList
      If H is an onerror event handler of a Window object
      Let the function have five arguments, named event, source, lineno, colno, and error.
      Otherwise
      Let the function have a single argument called event.
      Body
      The result of parsing body above.
      Scope
      1. If H is an element's event handler, then let Scope be NewObjectEnvironment(document, the global environment).

        Otherwise, H is a Window object's event handler: let Scope be the global environment.

      2. If form owner is not null, let Scope be NewObjectEnvironment(form owner, Scope).

      3. If element is not null, let Scope be NewObjectEnvironment(element, Scope).

      Strict
      The value of strict.
    11. Remove settings object's realm execution context from the JavaScript execution context stack.

    12. Set H's value to the result of creating a Web IDL callback function whose object reference is function and whose callback context is settings object.

  2. Return H's value.

8.1.5.2 Event handlers on elements, Document objects, and Window objects

The following are the event handlers (and their corresponding event handler event types) that must be supported by all HTML elements, as both event handler content attributes and event handler IDL attributes; and that must be supported by all Document and Window objects, as event handler IDL attributes:

Event handler Event handler event type
onabort abort
onauxclick auxclick
oncancel cancel
oncanplay canplay
oncanplaythrough canplaythrough
onchange change
onclick click
onclose close
oncontextmenu contextmenu
oncuechange cuechange
ondblclick dblclick
ondrag drag
ondragend dragend
ondragenter dragenter
ondragexit dragexit
ondragleave dragleave
ondragover dragover
ondragstart dragstart
ondrop drop
ondurationchange durationchange
onemptied emptied
onended ended
oninput input
oninvalid invalid
onkeydown keydown
onkeypress keypress
onkeyup keyup
onloadeddata loadeddata
onloadedmetadata loadedmetadata
onloadend loadend
onloadstart loadstart
onmousedown mousedown
onmouseenter mouseenter
onmouseleave mouseleave
onmousemove mousemove
onmouseout mouseout
onmouseover mouseover
onmouseup mouseup
onwheel wheel
onpause pause
onplay play
onplaying playing
onprogress progress
onratechange ratechange
onreset reset
onseeked seeked
onseeking seeking
onselect select
onshow show
onstalled stalled
onsubmit submit
onsuspend suspend
ontimeupdate timeupdate
ontoggle toggle
onvolumechange volumechange
onwaiting waiting

The following are the event handlers (and their corresponding event handler event types) that must be supported by all HTML elements other than body and frameset elements, as both event handler content attributes and event handler IDL attributes; that must be supported by all Document objects, as event handler IDL attributes; and that must be supported by all Window objects, as event handler IDL attributes on the Window objects themselves, and with corresponding event handler content attributes and event handler IDL attributes exposed on all body and frameset elements that are owned by that Window object's associated Document:

Event handler Event handler event type
onblur blur
onerror error
onfocus focus
onload load
onresize resize
onscroll scroll

The following are the event handlers (and their corresponding event handler event types) that must be supported by Window objects, as event handler IDL attributes on the Window objects themselves, and with corresponding event handler content attributes and event handler IDL attributes exposed on all body and frameset elements that are owned by that Window object's associated Document:

Event handler Event handler event type
onafterprint afterprint
onbeforeprint beforeprint
onbeforeunload beforeunload
onhashchange hashchange
onlanguagechange languagechange
onmessage message
onoffline offline
ononline online
onpagehide pagehide
onpageshow pageshow
onpopstate popstate
onrejectionhandled rejectionhandled
onstorage storage
onunhandledrejection unhandledrejection
onunload unload

The following are the event handlers (and their corresponding event handler event types) that must be supported by all HTML elements, as both event handler content attributes and event handler IDL attributes; and that must be supported by all Document objects, as event handler IDL attributes:

Event handler Event handler event type
oncut cut
oncopy copy
onpaste paste

The following are the event handlers (and their corresponding event handler event types) that must be supported on Document objects as event handler IDL attributes:

Event handler Event handler event type
onreadystatechange readystatechange
8.1.5.2.1 IDL definitions
[NoInterfaceObject]
interface GlobalEventHandlers {
  attribute EventHandler onabort;
  attribute EventHandler onauxclick;
  attribute EventHandler onblur;
  attribute EventHandler oncancel;
  attribute EventHandler oncanplay;
  attribute EventHandler oncanplaythrough;
  attribute EventHandler onchange;
  attribute EventHandler onclick;
  attribute EventHandler onclose;
  attribute EventHandler oncontextmenu;
  attribute EventHandler oncuechange;
  attribute EventHandler ondblclick;
  attribute EventHandler ondrag;
  attribute EventHandler ondragend;
  attribute EventHandler ondragenter;
  attribute EventHandler ondragexit;
  attribute EventHandler ondragleave;
  attribute EventHandler ondragover;
  attribute EventHandler ondragstart;
  attribute EventHandler ondrop;
  attribute EventHandler ondurationchange;
  attribute EventHandler onemptied;
  attribute EventHandler onended;
  attribute OnErrorEventHandler onerror;
  attribute EventHandler onfocus;
  attribute EventHandler oninput;
  attribute EventHandler oninvalid;
  attribute EventHandler onkeydown;
  attribute EventHandler onkeypress;
  attribute EventHandler onkeyup;
  attribute EventHandler onload;
  attribute EventHandler onloadeddata;
  attribute EventHandler onloadedmetadata;
  attribute EventHandler onloadend;
  attribute EventHandler onloadstart;
  attribute EventHandler onmousedown;
  [LenientThis] attribute EventHandler onmouseenter;
  [LenientThis] attribute EventHandler onmouseleave;
  attribute EventHandler onmousemove;
  attribute EventHandler onmouseout;
  attribute EventHandler onmouseover;
  attribute EventHandler onmouseup;
  attribute EventHandler onwheel;
  attribute EventHandler onpause;
  attribute EventHandler onplay;
  attribute EventHandler onplaying;
  attribute EventHandler onprogress;
  attribute EventHandler onratechange;
  attribute EventHandler onreset;
  attribute EventHandler onresize;
  attribute EventHandler onscroll;
  attribute EventHandler onseeked;
  attribute EventHandler onseeking;
  attribute EventHandler onselect;
  attribute EventHandler onshow;
  attribute EventHandler onstalled;
  attribute EventHandler onsubmit;
  attribute EventHandler onsuspend;
  attribute EventHandler ontimeupdate;
  attribute EventHandler ontoggle;
  attribute EventHandler onvolumechange;
  attribute EventHandler onwaiting;
};

[NoInterfaceObject]
interface WindowEventHandlers {
  attribute EventHandler onafterprint;
  attribute EventHandler onbeforeprint;
  attribute OnBeforeUnloadEventHandler onbeforeunload;
  attribute EventHandler onhashchange;
  attribute EventHandler onlanguagechange;
  attribute EventHandler onmessage;
  attribute EventHandler onoffline;
  attribute EventHandler ononline;
  attribute EventHandler onpagehide;
  attribute EventHandler onpageshow;
  attribute EventHandler onpopstate;
  attribute EventHandler onrejectionhandled;
  attribute EventHandler onstorage;
  attribute EventHandler onunhandledrejection;
  attribute EventHandler onunload;
};

[NoInterfaceObject]
interface DocumentAndElementEventHandlers {
  attribute EventHandler oncopy;
  attribute EventHandler oncut;
  attribute EventHandler onpaste;
};
8.1.5.3 Event firing

Certain operations and methods are defined as firing events on elements. For example, the click() method on the HTMLElement interface is defined as firing a click event on the element. [UIEVENTS]

Firing a synthetic mouse event named e at target, with an optional not trusted flag, means running these steps:

  1. Let event be the result of creating an event using MouseEvent.

  2. Initialize event's type attribute to e.

  3. Initialize event's bubbles and cancelable attributes to true.

  4. If the not trusted flag is set, initialize event's isTrusted attribute to false.

  5. Initialize event's ctrlKey, shiftKey, altKey, and metaKey attributes according to the current state of the key input device, if any (false for any keys that are not available).

  6. Initialize event's view attribute to target's node document's Window object, if any, and null otherwise.

  7. event's getModifierState() method is to return values appropriately describing the current state of the key input device.

  8. Return the result of dispatching event at target.

Firing a click event at target means firing a synthetic mouse event named click at target.

8.2 The WindowOrWorkerGlobalScope mixin

The WindowOrWorkerGlobalScope mixin is for use of APIs that are to be exposed on Window and WorkerGlobalScope objects.

Other standards are encouraged to further extend it using partial interface WindowOrWorkerGlobalScope { … }; along with an appropriate reference.

typedef (DOMString or Function) TimerHandler;

[NoInterfaceObject, Exposed=(Window,Worker)]
interface WindowOrWorkerGlobalScope {
  [Replaceable] readonly attribute USVString origin;

  // base64 utility methods
  DOMString btoa(DOMString data);
  DOMString atob(DOMString data);

  // timers
  long setTimeout(TimerHandler handler, optional long timeout = 0, any... arguments);
  void clearTimeout(optional long handle = 0);
  long setInterval(TimerHandler handler, optional long timeout = 0, any... arguments);
  void clearInterval(optional long handle = 0);

  // ImageBitmap
  Promise<ImageBitmap> createImageBitmap(ImageBitmapSource image, optional ImageBitmapOptions options);
  Promise<ImageBitmap> createImageBitmap(ImageBitmapSource image, long sx, long sy, long sw, long sh, optional ImageBitmapOptions options);
};
Window implements WindowOrWorkerGlobalScope;
WorkerGlobalScope implements WindowOrWorkerGlobalScope;
origin = self . origin

Returns the global object's origin, serialized as string.

Developers are strongly encouraged to use self.origin over location.origin. The former returns the origin of the environment, the latter of the URL of the environment. Imagine the following script executing in a document on https://stargate.example/:

var frame = document.createElement("iframe")
frame.onload = function() {
  var frameWin = frame.contentWindow
  console.log(frameWin.location.origin) // "null"
  console.log(frameWin.origin) // "https://stargate.example"
}
document.body.appendChild(frame)

self.origin is a more reliable security indicator.

The origin attribute's getter must return this object's relevant settings object's origin, serialized.

8.3 Base64 utility methods

Support: atob-btoaChrome for Android 56+Chrome 4+UC Browser for Android 11+iOS Safari 3.2+Firefox 2+IE 10+Samsung Internet 4+Opera Mini all+Android Browser 2.1+Safari 3.1+Edge 12+Opera 10.6+

Source: caniuse.com

The atob() and btoa() methods allow developers to transform content to and from the base64 encoding.

In these APIs, for mnemonic purposes, the "b" can be considered to stand for "binary", and the "a" for "ASCII". In practice, though, for primarily historical reasons, both the input and output of these functions are Unicode strings.

result = self . btoa( data )

Takes the input data, in the form of a Unicode string containing only characters in the range U+0000 to U+00FF, each representing a binary byte with values 0x00 to 0xFF respectively, and converts it to its base64 representation, which it returns.

Throws an "InvalidCharacterError" DOMException exception if the input string contains any out-of-range characters.

result = self . atob( data )

Takes the input data, in the form of a Unicode string containing base64-encoded binary data, decodes it, and returns a string consisting of characters in the range U+0000 to U+00FF, each representing a binary byte with values 0x00 to 0xFF respectively, corresponding to that binary data.

Throws an "InvalidCharacterError" DOMException if the input string is not valid base64 data.

The btoa(data) method must throw an "InvalidCharacterError" DOMException if data contains any character whose code point is greater than U+00FF. Otherwise, the user agent must convert data to a sequence of octets whose nth octet is the eight-bit representation of the code point of the nth character of data, and then must apply the base64 algorithm to that sequence of octets, and return the result. [RFC4648]

The atob(data) method, when invoked, must run the following steps:

  1. Let position be a pointer into data, initially pointing at the start of the string.

  2. Remove all ASCII whitespace from data.

  3. If the length of data divides by 4 leaving no remainder, then: if data ends with one or two U+003D EQUALS SIGN (=) characters, remove them from data.

  4. If the length of data divides by 4 leaving a remainder of 1, throw an "InvalidCharacterError" DOMException and abort these steps.

  5. If data contains a character that is not in the following list of characters and character ranges, throw an "InvalidCharacterError" DOMException and abort these steps:

  6. Let output be a string, initially empty.

  7. Let buffer be a buffer that can have bits appended to it, initially empty.

  8. While position does not point past the end of data, run these substeps:

    1. Find the character pointed to by position in the first column of the following table. Let n be the number given in the second cell of the same row.

      Character Number
      A0
      B1
      C2
      D3
      E4
      F5
      G6
      H7
      I8
      J9
      K10
      L11
      M12
      N13
      O14
      P15
      Q16
      R17
      S18
      T19
      U20
      V21
      W22
      X23
      Y24
      Z25
      a26
      b27
      c28
      d29
      e30
      f31
      g32
      h33
      i34
      j35
      k36
      l37
      m38
      n39
      o40
      p41
      q42
      r43
      s44
      t45
      u46
      v47
      w48
      x49
      y50
      z51
      052
      153
      254
      355
      456
      557
      658
      759
      860
      961
      +62
      /63
    2. Append to buffer the six bits corresponding to number, most significant bit first.

    3. If buffer has accumulated 24 bits, interpret them as three 8-bit big-endian numbers. Append the three characters with code points equal to those numbers to output, in the same order, and then empty buffer.

    4. Advance position by one character.

  9. If buffer is not empty, it contains either 12 or 18 bits. If it contains 12 bits, discard the last four and interpret the remaining eight as an 8-bit big-endian number. If it contains 18 bits, discard the last two and interpret the remaining 16 as two 8-bit big-endian numbers. Append the one or two characters with code points equal to those one or two numbers to output, in the same order.

    The discarded bits mean that, for instance, atob("YQ") and atob("YR") both return "a".

  10. Return output.

8.4 Dynamic markup insertion

APIs for dynamically inserting markup into the document interact with the parser, and thus their behavior varies depending on whether they are used with HTML documents (and the HTML parser) or XML documents (and the XML parser).

Document objects have a throw-on-dynamic-markup-insertion counter, which is used in conjunction with the create an element for the token algorithm to prevent custom element constructors from being able to use document.open(), document.close(), and document.write() when they are invoked by the parser. Initially, the counter must be set to zero.

8.4.1 Opening the input stream

The open() method comes in several variants with different numbers of arguments.

document = document . open( [ type [, replace ] ] )

Causes the Document to be replaced in-place, as if it was a new Document object, but reusing the previous object, which is then returned.

If the type argument is omitted or has the value "text/html", then the resulting Document has an HTML parser associated with it, which can be given data to parse using document.write(). Otherwise, all content passed to document.write() will be parsed as plain text.

If the replace argument is present and has the value "replace", the existing entries in the session history for the Document object are removed.

The method has no effect if the Document is still being parsed.

Throws an "InvalidStateError" DOMException if the Document is an XML document.

Throws an "InvalidStateError" DOMException if the parser is currently executing a custom element constructor.

window = document . open( url, name, features )

Works like the window.open() method.

Document objects have an ignore-opens-during-unload counter, which is used to prevent scripts from invoking the document.open() method (directly or indirectly) while the document is being unloaded. Initially, the counter must be set to zero.

When called with two arguments (or fewer), the document.open() method must act as follows:

  1. If the Document object is an XML document, then throw an "InvalidStateError" DOMException and abort these steps.

  2. If the Document object's throw-on-dynamic-markup-insertion counter is greater than zero, then throw an "InvalidStateError" DOMException and abort these steps.

  3. If the Document object is not an active document, then abort these steps.

  4. If the origin of the Document is not same origin with the origin of the responsible document specified by the entry settings object, throw a "SecurityError" DOMException and abort these steps.

  5. If the Document has an active parser whose script nesting level is greater than zero, then the method does nothing. Abort these steps and return the Document object on which the method was invoked.

    This basically causes document.open() to be ignored when it's called in an inline script found during parsing, while still letting it have an effect when called from a non-parser task such as a timer callback or event handler.

  6. Similarly, if the Document's ignore-opens-during-unload counter is greater than zero, then the method does nothing. Abort these steps and return the Document object on which the method was invoked.

    This basically causes document.open() to be ignored when it's called from a beforeunload pagehide, or unload event handler while the Document is being unloaded.

  7. Let type be the value of the first argument.

  8. If the second argument is an ASCII case-insensitive match for the value "replace", then let replace be true.

    Otherwise, if the browsing context's session history contains only one Document, and that was the about:blank Document created when the browsing context was created, and that Document has never had the unload a document algorithm invoked on it (e.g. by a previous call to document.open()), then let replace be true.

    Otherwise, let replace be false.

  9. Set the Document's salvageable state to false.

  10. Prompt to unload the Document object. If the user refused to allow the document to be unloaded, then abort these steps and return the Document object on which the method was invoked.

  11. Unload the Document object, with the recycle parameter set to true.

  12. Abort the Document.

  13. Unregister all event listeners registered on the Document node and its descendants.

  14. Remove any tasks associated with the Document in any task source.

  15. Remove all child nodes of the document, without firing any mutation events.

  16. Call the JavaScript InitializeHostDefinedRealm() abstract operation with the following customizations:

  17. Set window's associated Document to the Document.

  18. Set up a browsing context environment settings object with realm execution context.

  19. Replace the Document's singleton objects with new instances of those objects, created in window's Realm. (This includes in particular the History, ApplicationCache, and Navigator, objects, the various BarProp objects, the two Storage objects, the various HTMLCollection objects, and objects defined by other specifications, like Selection. It also includes all the Web IDL prototypes in the JavaScript binding, including the Document object's prototype.)

  20. Change the document's character encoding to UTF-8.

  21. If the Document is ready for post-load tasks, then set the Document object's reload override flag and set the Document's reload override buffer to the empty string.

  22. Set the Document's salvageable state back to true.

  23. Change the document's URL to the URL of the responsible document specified by the entry settings object.

  24. If the Document's iframe load in progress flag is set, set the Document's mute iframe load flag.

  25. Create a new HTML parser and associate it with the document. This is a script-created parser (meaning that it can be closed by the document.open() and document.close() methods, and that the tokenizer will wait for an explicit call to document.close() before emitting an end-of-file token). The encoding confidence is irrelevant.

  26. Set the current document readiness of the document to "loading".

  27. If type is an ASCII case-insensitive match for the string "replace", then, for historical reasons, set it to the string "text/html".

    Otherwise:

    If the type string contains a U+003B SEMICOLON character (;), remove the first such character and all characters from it up to the end of the string.

    Strip leading and trailing ASCII whitespace from type.

  28. If type is not now an ASCII case-insensitive match for the string "text/html", then act as if the tokenizer had emitted a start tag token with the tag name "pre" followed by a single U+000A LINE FEED (LF) character, then switch the HTML parser's tokenizer to the PLAINTEXT state.

  29. Remove all the entries in the browsing context's session history after the current entry. If the current entry is the last entry in the session history, then no entries are removed.

    This doesn't necessarily have to affect the user agent's user interface.

  30. Remove any tasks queued by the history traversal task source that are associated with any Document objects in the top-level browsing context's document family.

  31. Remove any earlier entries that share the same Document.
  32. If replace is false, then add a new entry, just before the last entry, and associate with the new entry the text that was parsed by the previous parser associated with the Document object, as well as the state of the document at the start of these steps. This allows the user to step backwards in the session history to see the page before it was blown away by the document.open() call. This new entry does not have a Document object, so a new one will be created if the session history is traversed to that entry.

  33. Set the Document's fired unload flag to false. (It could have been set to true during the unload step above.)

  34. Finally, set the insertion point to point at just before the end of the input stream (which at this point will be empty).

  35. Return the Document on which the method was invoked.

The document.open() method does not affect whether a Document is ready for post-load tasks or completely loaded.

When called with three arguments, the open() method on the Document object must call the open() method on the Window object of the Document object, with the same arguments as the original call to the open() method, and return whatever that method returned. If the Document object has no Window object, then the method must throw an "InvalidAccessError" DOMException.

8.4.2 Closing the input stream

document . close()

Closes the input stream that was opened by the document.open() method.

Throws an "InvalidStateError" DOMException if the Document is an XML document.

Throws an "InvalidStateError" DOMException if the parser is currently executing a custom element constructor.

The close() method must run the following steps:

  1. If the Document object is an XML document, then throw an "InvalidStateError" DOMException and abort these steps.

  2. If the Document object's throw-on-dynamic-markup-insertion counter is greater than zero, then throw an "InvalidStateError" DOMException and abort these steps.

  3. If there is no script-created parser associated with the document, then abort these steps.

  4. Insert an explicit "EOF" character at the end of the parser's input stream.

  5. If there is a pending parsing-blocking script, then abort these steps.

  6. Run the tokenizer, processing resulting tokens as they are emitted, and stopping when the tokenizer reaches the explicit "EOF" character or spins the event loop.

8.4.3 document.write()

document . write(text...)

In general, adds the given string(s) to the Document's input stream.

This method has very idiosyncratic behavior. In some cases, this method can affect the state of the HTML parser while the parser is running, resulting in a DOM that does not correspond to the source of the document (e.g. if the string written is the string "<plaintext>" or "<!--"). In other cases, the call can clear the current page first, as if document.open() had been called. In yet more cases, the method is simply ignored, or throws an exception. To make matters worse, the exact behavior of this method can in some cases be dependent on network latency, which can lead to failures that are very hard to debug. For all these reasons, use of this method is strongly discouraged.

Throws an "InvalidStateError" DOMException when invoked on XML documents.

Throws an "InvalidStateError" DOMException if the parser is currently executing a custom element constructor.

Document objects have an ignore-destructive-writes counter, which is used in conjunction with the processing of script elements to prevent external scripts from being able to use document.write() to blow away the document by implicitly calling document.open(). Initially, the counter must be set to zero.

The document.write(...) method must act as follows:

  1. If the method was invoked on an XML document, throw an "InvalidStateError" DOMException and abort these steps.

  2. If the Document object's throw-on-dynamic-markup-insertion counter is greater than zero, then throw an "InvalidStateError" DOMException and abort these steps.

  3. If the Document object is not an active document, then abort these steps.

  4. If the insertion point is undefined and either the Document's ignore-opens-during-unload counter is greater than zero or the Document's ignore-destructive-writes counter is greater than zero, abort these steps.

  5. If the insertion point is undefined, call the open() method on the document object (with no arguments). If the user refused to allow the document to be unloaded, then abort these steps. Otherwise, the insertion point will point at just before the end of the (empty) input stream.

  6. Insert the string consisting of the concatenation of all the arguments to the method into the input stream just before the insertion point.

  7. If the Document object's reload override flag is set, then append the string consisting of the concatenation of all the arguments to the method to the Document's reload override buffer.

  8. If there is no pending parsing-blocking script, have the HTML parser process the characters that were inserted, one at a time, processing resulting tokens as they are emitted, and stopping when the tokenizer reaches the insertion point or when the processing of the tokenizer is aborted by the tree construction stage (this can happen if a script end tag token is emitted by the tokenizer).

    If the document.write() method was called from script executing inline (i.e. executing because the parser parsed a set of script tags), then this is a reentrant invocation of the parser. If the parser pause flag is set, the tokenizer will abort immediately and no HTML will be parsed, per the tokenizer's parser pause flag check.

  9. Finally, return from the method.

8.4.4 document.writeln()

document . writeln(text...)

Adds the given string(s) to the Document's input stream, followed by a newline character. If necessary, calls the open() method implicitly first.

Throws an "InvalidStateError" DOMException when invoked on XML documents.

Throws an "InvalidStateError" DOMException if the parser is currently executing a custom element constructor.

The document.writeln(...) method, when invoked, must act as if the document.write() method had been invoked with the same argument(s), plus an extra argument consisting of a string containing a single line feed character (U+000A).

8.5 Timers

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

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

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

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

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

self . clearTimeout( handle )

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

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

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

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

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

self . clearInterval( handle )

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

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 list of active timers. Each entry in this lists is identified by a number, which must be unique within the list for the lifetime of the object that implements the WindowOrWorkerGlobalScope mixin.


The setTimeout() method must return the value returned by the timer initialization steps, passing them the method's arguments, the object on which the method for which the algorithm is running is implemented (a Window or WorkerGlobalScope object) as the method context, and the repeat flag set to false.

The setInterval() method must return the value returned by the timer initialization steps, passing them the method's arguments, the object on which the method for which the algorithm is running is implemented (a Window or WorkerGlobalScope object) as the method context, and the repeat flag set to true.

The clearTimeout() and clearInterval() methods must clear the entry identified as handle from the list of active timers of the WindowOrWorkerGlobalScope object on which the method was invoked, if any, where handle is the argument passed to the method. (If handle does not identify an entry in the list of active timers of the WindowOrWorkerGlobalScope object on which the method was invoked, the method does nothing.)

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


The timer initialization steps, which are invoked with some method arguments, a method context, a repeat flag which can be true or false, and optionally (and only if the repeat flag is true) a previous handle, are as follows:

  1. Let method context proxy be method context if that is a WorkerGlobalScope object, or else the WindowProxy that corresponds to method context.

  2. If previous handle was provided, let handle be previous handle; otherwise, let handle be a user-agent-defined integer that is greater than zero that will identify the timeout to be set by this call in the list of active timers.

  3. If previous handle was not provided, add an entry to the list of active timers for handle.

  4. Let callerRealm be the current Realm Record, and calleeRealm be method context's JavaScript realm.

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

    1. If the entry for handle in the list of active timers has been cleared, then abort this task's substeps.

    2. Run the appropriate set of steps from the following list:

      If the first method argument is a Function

      Invoke the Function. Use the third and subsequent method arguments (if any) as the arguments for invoking the Function. Use method context proxy as the callback this value.

      Otherwise
      1. Perform HostEnsureCanCompileStrings(callerRealm, calleeRealm). If this throws an exception, report the exception.

      2. Let script source be the first method argument.

      3. Let settings object be method context's environment settings object.

      4. Let script be the result of creating a classic script using script source and settings object.

      5. Run the classic script script.

    3. If the repeat flag is true, then call timer initialization steps again, passing them the same method arguments, the same method context, with the repeat flag still set to true, and with the previous handle set to handler.

  6. Let timeout be the second method argument.

  7. If the 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 zero.

    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.

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

  9. Increment nesting level by one.

  10. Let task's timer nesting level be nesting level.

  11. Return handle, and then continue running this algorithm in parallel.

  12. If method context is a Window object, wait until the Document associated with method context has been fully active for a further timeout milliseconds (not necessarily consecutively).

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

  13. Wait until any invocations of this algorithm that had the same method context, that started before this one, and whose timeout is equal to or less than this one's, have completed.

    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);
  14. Optionally, wait a further user-agent 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.

  15. Queue the task task.

    Once the task has been processed, if the repeat flag is false, it is safe to remove the entry for handle from the list of active timers (there is no way for the entry's existence to be detected past this point, so it does not technically matter one way or the other).

The task source for these tasks is the timer task source.

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 handle = setTimeout(rescheduleWork, 0); // preschedule next iteration
  if (doExpensiveWork())
    clearTimeout(handle); // clear the timeout if we don't need it
}

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

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

8.6 User prompts

8.6.1 Simple dialogs

window . alert(message)

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

result = window . confirm(message)

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] )

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.

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.

The alert(message) method, when invoked, must run the following steps:

  1. If the event loop's termination nesting level is non-zero, optionally abort these steps.

  2. If the active sandboxing flag set of this Window object's associated Document has the sandboxed modals flag set, then abort these steps.

  3. Optionally, abort these steps. (For example, the user agent might give the user the option to ignore all alerts, and would thus abort at this step whenever the method was invoked.)

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

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

  6. Show message to the user.

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

The confirm(message) method, when invoked, must run the following steps:

  1. If the event loop's termination nesting level is non-zero, optionally abort these steps, returning false.

  2. If the active sandboxing flag set of this Window object's associated Document has the sandboxed modals flag set, then abort these steps.

  3. Optionally, return false and abort these steps. (For example, the user agent might give the user the option to ignore all prompts, and would thus abort at this step whenever the method was invoked.)

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

  5. Show message to the user, and ask the user to respond with a positive or negative response.

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

  7. If the user responded positively, return true; otherwise, the user responded negatively: return false.

The prompt(message, default) method, when invoked, must run the following steps:

  1. If the event loop's termination nesting level is non-zero, optionally abort these steps, returning null.

  2. If the active sandboxing flag set of this Window object's associated Document has the sandboxed modals flag set, then abort these steps.

  3. Optionally, return null and abort these steps. (For example, the user agent might give the user the option to ignore all prompts, and would thus abort at this step whenever the method was invoked.)

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

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

  6. Show message to the user, and ask the user to either respond with a string value or abort. The response must be defaulted to the value given by default.

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

  8. If the user aborts, then return null; otherwise, return the string that the user responded with.

8.6.2 Printing

window . print()

Prompts the user to print the page.

When the print() method is invoked, if the Document is ready for post-load tasks, then the user agent must run the printing steps in parallel. Otherwise, the user agent must only set the print when loaded flag on the Document.

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 are as follows:

Spec bugs: 27864

  1. The user agent may display a message to the user or abort these steps (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 this Window object's associated Document has the sandboxed modals flag set, then abort these steps.

    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 Window object of the Document that is being printed, as well as any nested browsing contexts in it.

    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 the 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 Window object of the Document that is being printed, as well as any nested browsing contexts in it.

    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.

8.7 System state and capabilities

8.7.1 The Navigator object

The navigator attribute of the Window interface must return an instance of the Navigator interface, which represents the identity and state of the user agent (the client), and allows Web pages to register themselves as potential protocol and content handlers:

interface Navigator {
  // objects implementing this interface also implement the interfaces given below
};
Navigator implements NavigatorID;
Navigator implements NavigatorLanguage;
Navigator implements NavigatorOnLine;
Navigator implements NavigatorContentUtils;
Navigator implements NavigatorCookies;
Navigator implements NavigatorPlugins;
Navigator implements NavigatorConcurrentHardware;

These interfaces are defined separately so that WorkerNavigator can re-use parts of the Navigator interface.

8.7.1.1 Client identification
[NoInterfaceObject, Exposed=(Window,Worker)]
interface NavigatorID {
  readonly attribute DOMString appCodeName; // constant "Mozilla"
  readonly attribute DOMString appName; // constant "Netscape"
  readonly attribute DOMString appVersion;
  readonly attribute DOMString platform;
  readonly attribute DOMString product; // constant "Gecko"
  [Exposed=Window] readonly attribute DOMString productSub;
  readonly attribute DOMString userAgent;
  [Exposed=Window] readonly attribute DOMString vendor;
  [Exposed=Window] readonly attribute DOMString vendorSub; // constant ""
};

In certain cases, despite the best efforts of the entire industry, Web browsers have bugs and limitations that Web authors are forced to work around.

This section defines a collection of attributes that can be used to determine, from script, the kind of user agent in use, in order to work around these issues.

The user agent has a navigator compatibility mode, which is either Chrome, Gecko, or WebKit.

The navigator compatibility mode constrains the NavigatorID interface to the combinations of attribute values and presence of taintEnabled() and oscpu that are known to be compatible with existing Web content.

Client detection should always be limited to detecting known current versions; future versions and unknown versions should always be assumed to be fully compliant.

window . navigator . appCodeName

Returns the string "Mozilla".

window . navigator . appName

Returns the string "Netscape".

window . navigator . appVersion

Returns the version of the browser.

window . navigator . platform

Returns the name of the platform.

window . navigator . product

Returns the string "Gecko".

window . navigator . productSub

Returns either the string "20030107", or the string "20100101".

window . navigator . userAgent

Returns the complete `User-Agent` header.

window . navigator . vendor

Returns either the empty string, the string "Apple Computer, Inc.", or the string "Google Inc.".

window . navigator . vendorSub

Returns the empty string.

appCodeName

Must return the string "Mozilla".

appName

Must return the string "Netscape".

appVersion

Must return either the string "4.0" or a string representing the version of the browser in detail, e.g. "1.0 (VMS; en-US) Mellblomenator/9000".

platform

Must return either the empty string or a string representing the platform on which the browser is executing, e.g. "MacIntel", "Win32", "FreeBSD i386", "WebTV OS".

product

Must return the string "Gecko".

productSub

Must return the appropriate string from the following list:

If the navigator compatibility mode is Chrome or WebKit

The string "20030107".

If the navigator compatibility mode is Gecko

The string "20100101".

userAgent

Must return the default `User-Agent` value.

vendor

Must return the appropriate string from the following list:

If the navigator compatibility mode is Chrome

The string "Google Inc.".

If the navigator compatibility mode is Gecko

The empty string.

If the navigator compatibility mode is WebKit

The string "Apple Computer, Inc.".

vendorSub

Must return the empty string.

If the navigator compatibility mode is Gecko, then the user agent must also support the following partial interface:

partial interface NavigatorID {
  [Exposed=Window] boolean taintEnabled(); // constant false
  [Exposed=Window] readonly attribute DOMString oscpu;
};

The taintEnabled() method must return false.

The oscpu attribute's getter must return either the empty string or a string representing the platform on which the browser is executing, e.g. "Windows NT 10.0; Win64; x64", "Linux x86_64".

Any information in this API that varies from user to user can be used to profile the user. In fact, if enough such information is available, a user can actually be uniquely identified. For this reason, user agent implementors are strongly urged to include as little information in this API as possible. (This is a fingerprinting vector.)

8.7.1.2 Language preferences
[NoInterfaceObject, Exposed=(Window,Worker)]
interface NavigatorLanguage {
  readonly attribute DOMString language;
  readonly attribute FrozenArray<DOMString> languages;
};
window . navigator . language

Returns a language tag representing the user's preferred language.

window . navigator . languages

Returns an array of language tags representing the user's preferred languages, with the most preferred language first.

The most preferred language is the one returned by navigator.language.

A languagechange event is fired at the Window or WorkerGlobalScope object when the user agent's understanding of what the user's preferred languages are changes.

language

Must return a valid BCP 47 language tag representing either a plausible language or the user's most preferred language. [BCP47]

languages

Must return a frozen array of valid BCP 47 language tags representing either one or more plausible languages, or the user's preferred languages, ordered by preference with the most preferred language first. The same object must be returned until the user agent needs to return different values, or values in a different order. [BCP47]

Whenever the user agent needs to make the navigator.languages attribute of a Window or WorkerGlobalScope object return a new set of language tags, the user agent must queue a task to fire an event named languagechange at the Window or WorkerGlobalScope object and wait until that task begins to be executed before actually returning a new value.

The task source for this task is the DOM manipulation task source.

To determine a plausible language, the user agent should bear in mind the following:

To avoid introducing any more fingerprinting vectors, user agents should use the same list for the APIs defined in this function as for the HTTP `Accept-Language` header. (This is a fingerprinting vector.)

8.7.1.3 Custom scheme and content handlers: the registerProtocolHandler() and registerContentHandler() methods

Support: registerprotocolhandlerChrome for Android NoneChrome 13+UC Browser for Android NoneiOS Safari NoneFirefox 3+IE NoneSamsung Internet NoneOpera Mini NoneAndroid Browser NoneSafari NoneEdge NoneOpera 11.6+

Source: caniuse.com

[NoInterfaceObject]
interface NavigatorContentUtils {
  // content handler registration
  void registerProtocolHandler(DOMString scheme, USVString url, DOMString title);
  void registerContentHandler(DOMString mimeType, USVString url, DOMString title);
  DOMString isProtocolHandlerRegistered(DOMString scheme, USVString url);
  DOMString isContentHandlerRegistered(DOMString mimeType, USVString url);
  void unregisterProtocolHandler(DOMString scheme, USVString url);
  void unregisterContentHandler(DOMString mimeType, USVString url);
};

The registerProtocolHandler() method allows Web sites to register themselves as possible handlers for particular schemes. For example, an online telephone messaging service could register itself as a handler of the sms: scheme, so that if the user clicks on such a link, they are given the opportunity to use that Web site. Analogously, the registerContentHandler() method allows Web sites to register themselves as possible handlers for content in a particular MIME type. For example, the same online telephone messaging service could register itself as a handler for text/vcard files, so that if the user has no native application capable of handling vCards, their Web browser can instead suggest they use that site to view contact information stored on vCards that they open. [SMS] [RFC6350]

window . navigator . registerProtocolHandler(scheme, url, title)
window . navigator . registerContentHandler(mimeType, url, title)

Registers a handler for the given scheme or content type, at the given URL, with the given title.

The string "%s" in the URL is used as a placeholder for where to put the URL of the content to be handled.

Throws a "SecurityError" DOMException if the user agent blocks the registration (this might happen if trying to register as a handler for "http", for instance).

Throws a "SyntaxError" DOMException if the "%s" string is missing in the URL.

User agents may, within the constraints described in this section, do whatever they like when the methods are called. A UA could, for instance, prompt the user and offer the user the opportunity to add the site to a shortlist of handlers, or make the handlers their default, or cancel the request. UAs could provide such a UI through modal UI or through a non-modal transient notification interface. UAs could also simply silently collect the information, providing it only when relevant to the user.

User agents should keep track of which sites have registered handlers (even if the user has declined such registrations) so that the user is not repeatedly prompted with the same request.

The arguments to the methods have the following meanings and corresponding implementation requirements. The requirements that involve throwing exceptions must be processed in the order given below, stopping at the first exception thrown. (So the exceptions for the first argument take precedence over the exceptions for the second argument.)

scheme (registerProtocolHandler() only)

A scheme, such as "mailto" or "web+auth". The scheme must be compared in an ASCII case-insensitive manner by user agents for the purposes of comparing with the scheme part of URLs that they consider against the list of registered handlers.

The scheme value, if it contains a colon (as in "mailto:"), will never match anything, since schemes don't contain colons.

If the registerProtocolHandler() method is invoked with a scheme that is neither a safelisted scheme nor a scheme whose value starts with the substring "web+" and otherwise contains only ASCII lower alphas, and whose length is at least five characters (including the "web+" prefix), the user agent must throw a "SecurityError" DOMException.

The following schemes are the safelisted schemes:

This list can be changed. If there are schemes that ought to be added, please send feedback.

This list excludes any schemes that could reasonably be expected to be supported inline, e.g. in an iframe, such as http or (more theoretically) gopher. If those were supported, they could potentially be used in man-in-the-middle attacks, by replacing pages that have frames with such content with content under the control of the protocol handler. If the user agent has native support for the schemes, this could further be used for cookie-theft attacks.

mimeType (registerContentHandler() only)

A MIME type, such as model/vnd.flatland.3dml or application/vnd.google-earth.kml+xml. The MIME type must be compared in an ASCII case-insensitive manner by user agents for the purposes of comparing with MIME types of documents that they consider against the list of registered handlers.

User agents must compare the given values only to the MIME type/subtype parts of content types, not to the complete type including parameters. Thus, if mimeType values passed to this method include characters such as commas or whitespace, or include MIME parameters, then the handler being registered will never be used.

The type is compared to the MIME type used by the user agent after the sniffing algorithms have been applied.

If the registerContentHandler() method is invoked with a MIME type that is in the type blocklist or that the user agent has deemed a privileged type, the user agent must throw a "SecurityError" DOMException.

The following MIME types are in the type blocklist:

This list can be changed. If there are MIME types that ought to be added, please send feedback.

url

A string used to build the URL of the page that will handle the requests.

User agents must throw a "SyntaxError" DOMException if the url argument passed to one of these methods does not contain the exact literal string "%s".

User agents must throw a "SyntaxError" DOMException if parsing the url argument relative to the relevant settings object of this NavigatorContentUtils object is not successful.

The resulting URL string would by definition not be a valid URL string as it would include the string "%s" which is not a valid component in a URL.

User agents must throw a "SecurityError" DOMException if the resulting URL record has an origin that differs from the origin specified by the relevant settings object of this NavigatorContentUtils object.

This is forcibly the case if the %s placeholder is in the scheme, host, or port parts of the URL.

The resulting URL string is the proto-URL. It identifies the handler for the purposes of the methods described below.

When the user agent uses this handler, it must replace the first occurrence of the exact literal string "%s" in the url argument with an escaped version of the absolute URL of the content in question (as defined below), then parse the resulting URL, relative to the relevant settings object of the NavigatorContentUtils object on which the registerContentHandler() or registerProtocolHandler() method was invoked, and then navigate an appropriate browsing context to the resulting URL.

To get the escaped version of the absolute URL of the content in question, the user agent must replace every character in that absolute URL that is not a character in the URL default encode set with the result of UTF-8 percent encoding that character.

If the user had visited a site at https://example.com/ that made the following call:

navigator.registerContentHandler('application/x-soup', 'soup?url=%s', 'SoupWeb™')

...and then, much later, while visiting https://www.example.net/, clicked on a link such as:

<a href="chickenkïwi.soup">Download our Chicken Kïwi soup!</a>

...then, assuming this chickenkïwi.soup file was served with the MIME type application/x-soup, the UA might navigate to the following URL:

https://example.com/soup?url=https://www.example.net/chickenk%C3%AFwi.soup

This site could then fetch the chickenkïwi.soup file and do whatever it is that it does with soup (synthesize it and ship it to the user, or whatever).

title

A descriptive title of the handler, which the UA might use to remind the user what the site in question is.

This section does not define how the pages registered by these methods are used, beyond the requirements on how to process the url value (see above). To some extent, the processing model for navigating across documents defines some cases where these methods are relevant, but in general UAs may use this information wherever they would otherwise consider handing content to native plugins or helper applications.

UAs must not use registered content handlers to handle content that was returned as part of a non-GET transaction (or rather, as part of any non-idempotent transaction), as the remote site would not be able to fetch the same data.


In addition to the registration methods, there are also methods for determining if particular handlers have been registered, and for unregistering handlers.

state = window . navigator . isProtocolHandlerRegistered(scheme, url)
state = window . navigator . isContentHandlerRegistered(mimeType, url)

Returns one of the following strings describing the state of the handler given by the arguments:

new
Indicates that no attempt has been made to register the given handler (or that the handler has been unregistered). It would be appropriate to promote the availability of the handler or to just automatically register the handler.
registered
Indicates that the given handler has been registered or that the site is blocked from registering the handler. Trying to register the handler again would have no effect.
declined
Indicates that the given handler has been offered but was rejected. Trying to register the handler again may prompt the user again.
window . navigator . unregisterProtocolHandler(scheme, url)
window . navigator . unregisterContentHandler(mimeType, url)

Unregisters the handler given by the arguments.

The isProtocolHandlerRegistered() method must return the handler state string that most closely describes the current state of the handler described by the two arguments to the method, where the first argument gives the scheme and the second gives the string used to build the URL of the page that will handle the requests. (This is a fingerprinting vector.)

The first argument must be compared to the schemes for which custom protocol handlers are registered in an ASCII case-insensitive manner to find the relevant handlers.

The second argument must be preprocessed as described below, and if that is successful, must then be matched against the proto-URLs of the relevant handlers to find the described handler.


The isContentHandlerRegistered() method must return the handler state string that most closely describes the current state of the handler described by the two arguments to the method, where the first argument gives the MIME type and the second gives the string used to build the URL of the page that will handle the requests. (This is a fingerprinting vector.)

The first argument must be compared to the MIME types for which custom content handlers are registered in an ASCII case-insensitive manner to find the relevant handlers.

The second argument must be preprocessed as described below, and if that is successful, must then be matched against the proto-URLs of the relevant handlers to find the described handler.


The handler state strings are the following strings. Each string describes several situations, as given by the following list.

new
The described handler has never been registered for the given scheme or type.
The described handler was once registered for the given scheme or type, but the site has since unregistered it. If the handler were to be reregistered, the user would be notified accordingly.
The described handler was once registered for the given scheme or type, but the site has since unregistered it, but the user has indicated that the site is to be blocked from registering the type again, so the user agent would ignore further registration attempts.
registered
An attempt was made to register the described handler for the given scheme or type, but the user has not yet been notified, and the user agent would ignore further registration attempts. (Maybe the user agent batches registration requests to display them when the user requests to be notified about them, and the user has not yet requested that the user agent notify it of the previous registration attempt.)
The described handler is registered for the given scheme or type (maybe, or maybe not, as the default handler).
The described handler is permanently blocked from being (re)registered. (Maybe the user marked the registration attempt as spam, or blocked the site for other reasons.)
declined
An attempt was made to register the described handler for the given scheme or type, but the user has not yet been notified; however, the user might be notified if another registration attempt were to be made. (Maybe the last registration attempt was made while the page was in the background and the user closed the page without looking at it, and the user agent requires confirmation for this registration attempt.)
An attempt was made to register the described handler for the given scheme or type, but the user has not yet responded.
An attempt was made to register the described handler for the given scheme or type, but the user declined the offer. The user has not indicated that the handler is to be permanently blocked, however, so another attempt to register the described handler might result in the user being prompted again.
The described handler was once registered for the given scheme or type, but the user has since removed it. The user has not indicated that the handler is to be permanently blocked, however, so another attempt to register the described handler might result in the user being prompted again.

The unregisterProtocolHandler() method must unregister the handler described by the two arguments to the method, where the first argument gives the scheme and the second gives the string used to build the URL of the page that will handle the requests.

The first argument must be compared to the schemes for which custom protocol handlers are registered in an ASCII case-insensitive manner to find the relevant handlers.

The second argument must be preprocessed as described below, and if that is successful, must then be matched against the proto-URLs of the relevant handlers to find the described handler.


The unregisterContentHandler() method must unregister the handler described by the two arguments to the method, where the first argument gives the MIME type and the second gives the string used to build the URL of the page that will handle the requests.

The first argument must be compared to the MIME types for which custom content handlers are registered in an ASCII case-insensitive manner to find the relevant handlers.

The second argument must be preprocessed as described below, and if that is successful, must then be matched against the proto-URLs of the relevant handlers to find the described handler.


The second argument of the four methods described above must be preprocessed as follows:

  1. If the string does not contain the substring "%s", abort these steps. There's no matching handler.

  2. Parse the string relative to the relevant settings object of this NavigatorContentUtils object. If this fails, then throw a "SyntaxError" DOMException.

  3. If the resulting URL record's origin is not the same origin as the origin of the relevant settings object of this NavigatorContentUtils object, throw a "SecurityError" DOMException.

  4. Return the resulting URL string as the result of preprocessing the argument.

8.7.1.3.1 Security and privacy

These mechanisms can introduce a number of concerns, in particular privacy concerns.

Hijacking all Web usage. User agents should not allow schemes that are key to its normal operation, such as an HTTP(S) scheme, to be rerouted through third-party sites. This would allow a user's activities to be trivially tracked, and would allow user information, even in secure connections, to be collected.

Hijacking defaults. User agents are strongly urged to not automatically change any defaults, as this could lead the user to send data to remote hosts that the user is not expecting. New handlers registering themselves should never automatically cause those sites to be used.

Registration spamming. User agents should consider the possibility that a site will attempt to register a large number of handlers, possibly from multiple domains (e.g. by redirecting through a series of pages each on a different domain, and each registering a handler for video/mpeg — analogous practices abusing other Web browser features have been used by pornography Web sites for many years). User agents should gracefully handle such hostile attempts, protecting the user.

Misleading titles. User agents should not rely wholly on the title argument to the methods when presenting the registered handlers to the user, since sites could easily lie. For example, a site hostile.example.net could claim that it was registering the "Cuddly Bear Happy Content Handler". User agents should therefore use the handler's domain in any UI along with any title.

Hostile handler metadata. User agents should protect against typical attacks against strings embedded in their interface, for example ensuring that markup or escape characters in such strings are not executed, that null bytes are properly handled, that over-long strings do not cause crashes or buffer overruns, and so forth.

Leaking Intranet URLs. The mechanism described in this section can result in secret Intranet URLs being leaked, in the following manner:

  1. The user registers a third-party content handler as the default handler for a content type.
  2. The user then browses their corporate Intranet site and accesses a document that uses that content type.
  3. The user agent contacts the third party and hands the third party the URL to the Intranet content.

No actual confidential file data is leaked in this manner, but the URLs themselves could contain confidential information. For example, the URL could be https://www.corp.example.com/upcoming-aquisitions/the-sample-company.egf, which might tell the third party that Example Corporation is intending to merge with The Sample Company. Implementors might wish to consider allowing administrators to disable this feature for certain subdomains, content types, or schemes.

Leaking secure URLs. User agents should not send HTTPS URLs to third-party sites registered as content handlers without the user's informed consent, for the same reason that user agents sometimes avoid sending `Referer` (sic) HTTP headers from secure sites to third-party sites.

Leaking credentials. User agents must never send username or password information in the URLs that are escaped and included sent to the handler sites. User agents may even avoid attempting to pass to Web-based handlers the URLs of resources that are known to require authentication to access, as such sites would be unable to access the resources in question without prompting the user for credentials themselves (a practice that would require the user to know whether to trust the third-party handler, a decision many users are unable to make or even understand).

Interface interference. User agents should be prepared to handle intentionally long arguments to the methods. For example, if the user interface exposed consists of an "accept" button and a "deny" button, with the "accept" binding containing the name of the handler, it's important that a long name not cause the "deny" button to be pushed off the screen.

Fingerprinting users. Since a site can detect if it has attempted to register a particular handler or not, whether or not the user responds, the mechanism can be used to store data. User agents are therefore strongly urged to treat registrations in the same manner as cookies: clearing cookies for a site should also clear all registrations for that site, and disabling cookies for a site should also disable registrations.

8.7.1.3.2 Sample user interface

This section is non-normative.

A simple implementation of this feature for a desktop Web browser might work as follows.

The registerContentHandler() method could display a modal dialog box:

The modal dialog box could have the title 'Content Handler Registration', and could say 'This Web page: Kittens at work http://kittens.example.org/ ...would like permission to handle files of type: application/x-meowmeow using the following Web-based application: Kittens-at-work displayer http://kittens.example.org/?show=%s Do you trust the administrators of the "kittens.example.org" domain?' with two buttons, 'Trust kittens.example.org' and 'Cancel'.

In this dialog box, "Kittens at work" is the title of the page that invoked the method, "http://kittens.example.org/" is the URL of that page, "application/x-meowmeow" is the string that was passed to the registerContentHandler() method as its first argument (mimeType), "http://kittens.example.org/?show=%s" was the second argument (url), and "Kittens-at-work displayer" was the third argument (title).

If the user clicks the Cancel button, then nothing further happens. If the user clicks the "Trust" button, then the handler is remembered.

When the user then attempts to fetch a URL that uses the "application/x-meowmeow" MIME type, then it might display a dialog as follows:

The dialog box could have the title 'Unknown File Type' and could say 'You have attempted to access:' followed by a URL, followed by a prompt such as 'How would you like FerretBrowser to handle this resource?' with three radio buttons, one saying 'Contact the FerretBrowser plugin registry to see if there is an official way to handle this resource.', one saying 'Pass this URL to a local application' with an application selector, and one saying 'Pass this URL to the "Kittens-at-work displayer" application at "kittens.example.org"', with a checkbox labeled 'Always do this for resources using the "application/x-meowmeow" type in future.', and with two buttons, 'Ok' and 'Cancel'.

In this dialog, the third option is the one that was primed by the site registering itself earlier.

If the user does select that option, then the browser, in accordance with the requirements described in the previous two sections, will redirect the user to "http://kittens.example.org/?show=data%3Aapplication/x-meowmeow;base64,S2l0dGVucyBhcmUgdGhlIGN1dGVzdCE%253D".

The registerProtocolHandler() method would work equivalently, but for schemes instead of unknown content types.

8.7.1.4 Cookies
[NoInterfaceObject]
interface NavigatorCookies {
  readonly attribute boolean cookieEnabled;
};
window . navigator . cookieEnabled

Returns false if setting a cookie will be ignored, and true otherwise.

The cookieEnabled attribute must return true if the user agent attempts to handle cookies according to the cookie specification, and false if it ignores cookie change requests. [COOKIES]

8.7.1.5 Plugins
[NoInterfaceObject]
interface NavigatorPlugins {
  [SameObject] readonly attribute PluginArray plugins;
  [SameObject] readonly attribute MimeTypeArray mimeTypes;
  boolean javaEnabled();
};

[LegacyUnenumerableNamedProperties]
interface PluginArray {
  void refresh(optional boolean reload = false);
  readonly attribute unsigned long length;
  getter Plugin? item(unsigned long index);
  getter Plugin? namedItem(DOMString name);
};

[LegacyUnenumerableNamedProperties]
interface MimeTypeArray {
  readonly attribute unsigned long length;
  getter MimeType? item(unsigned long index);
  getter MimeType? namedItem(DOMString name);
};

[LegacyUnenumerableNamedProperties]
interface Plugin {
  readonly attribute DOMString name;
  readonly attribute DOMString description;
  readonly attribute DOMString filename;
  readonly attribute unsigned long length;
  getter MimeType? item(unsigned long index);
  getter MimeType? namedItem(DOMString name);
};

interface MimeType {
  readonly attribute DOMString type;
  readonly attribute DOMString description;
  readonly attribute DOMString suffixes; // comma-separated
  readonly attribute Plugin enabledPlugin;
};
window . navigator . plugins . refresh( [ refresh ] )

Updates the lists of supported plugins and MIME types for this page, and reloads the page if the lists have changed.

window . navigator . plugins . length

Returns the number of plugins, represented by Plugin objects, that the user agent reports.

plugin = window . navigator . plugins . item(index)
window . navigator . plugins[index]

Returns the specified Plugin object.

plugin = window . navigator . plugins . item(name)
window . navigator . plugins[name]

Returns the Plugin object for the plugin with the given name.

window . navigator . mimeTypes . length

Returns the number of MIME types, represented by MimeType objects, supported by the plugins that the user agent reports.

mimeType = window . navigator . mimeTypes . item(index)
window . navigator . mimeTypes[index]

Returns the specified MimeType object.

mimeType = window . navigator . mimeTypes . item(name)
window . navigator . mimeTypes[name]

Returns the MimeType object for the given MIME type.

plugin . name

Returns the plugin's name.

plugin . description

Returns the plugin's description.

plugin . filename

Returns the plugin library's filename, if applicable on the current platform.

plugin . length

Returns the number of MIME types, represented by MimeType objects, supported by the plugin.

mimeType = plugin . item(index)
plugin[index]

Returns the specified MimeType object.

mimeType = plugin . item(name)
plugin[name]

Returns the MimeType object for the given MIME type.

mimeType . type

Returns the MIME type.

mimeType . description

Returns the MIME type's description.

mimeType . suffixes

Returns the MIME type's typical file extensions, in a comma-separated list.

mimeType . enabledPlugin

Returns the Plugin object that implements this MIME type.

window . navigator . javaEnabled()

Returns true if there's a plugin that supports the MIME type "application/x-java-vm".

The navigator.plugins attribute must return a PluginArray object.

The navigator.mimeTypes attribute must return a MimeTypeArray object.


A PluginArray object represents none, some, or all of the plugins supported by the user agent, each of which is represented by a Plugin object. Each of these Plugin objects may be hidden plugins. A hidden plugin can't be enumerated, but can still be inspected by using its name.

The fewer plugins are represented by the PluginArray object, and of those, the more that are hidden, the more the user's privacy will be protected. Each exposed plugin increases the number of bits that can be derived for fingerprinting. Hiding a plugin helps, but unless it is an extremely rare plugin, it is likely that a site attempting to derive the list of plugins can still determine whether the plugin is supported or not by probing for it by name (the names of popular plugins are widely known). Therefore not exposing a plugin at all is preferred. Unfortunately, many legacy sites use this feature to determine, for example, which plugin to use to play video. Not exposing any plugins at all might therefore not be entirely plausible.

The PluginArray objects created by a user agent must not be live. The set of plugins represented by the objects must not change once an object is created, except when it is updated by the refresh() method.

Each plugin represented by a PluginArray can support a number of MIME types. For each such plugin, the user agent must pick one or more of these MIME types to be those that are explicitly supported.

The explicitly supported MIME types of a plugin are those that are exposed through the Plugin and MimeTypeArray interfaces. As with plugins themselves, any variation between users regarding what is exposed allows sites to fingerprint users. User agents are therefore encouraged to expose the same MIME types for all users of a plugin, regardless of the actual types supported... at least, within the constraints imposed by compatibility with legacy content.

The supported property indices of a PluginArray object are the numbers from zero to the number of non-hidden plugins represented by the object, if any. (This is a fingerprinting vector.)

The length attribute must return the number of non-hidden plugins represented by the object. (This is a fingerprinting vector.)

The item() method of a PluginArray object must return null if the argument is not one of the object's supported property indices, and otherwise must return the result of running the following steps, using the method's argument as index:

  1. Let list be the Plugin objects representing the non-hidden plugins represented by the PluginArray object.

  2. Sort list alphabetically by the name of each Plugin.

  3. Return the indexth entry in list.

It is important for privacy that the order of plugins not leak additional information, e.g. the order in which plugins were installed.

The supported property names of a PluginArray object are the values of the name attributes of all the Plugin objects represented by the PluginArray object. (This is a fingerprinting vector.)

The namedItem() method of a PluginArray object must return null if the argument is not one of the object's supported property names, and otherwise must return the Plugin object, of those represented by the PluginArray object, that has a name equal to the method's argument.

The refresh() method of the PluginArray object of a Navigator object, when invoked, must check to see if any plugins have been installed or reconfigured since the user agent created the PluginArray object. If so, and the method's argument is true, then the user agent must act as if the location.reload() method was called instead. Otherwise, the user agent must update the PluginArray object and MimeTypeArray object created for attributes of that Navigator object, and the Plugin and MimeType objects created for those PluginArray and MimeTypeArray objects, using the same Plugin objects for cases where the name is the same, and the same MimeType objects for cases where the type is the same, and creating new objects for cases where there were no matching objects immediately prior to the refresh() call. Old Plugin and MimeType objects must continue to return the same values that they had prior to the update, though naturally now the data is stale and may appear inconsistent (for example, an old MimeType entry might list as its enabledPlugin a Plugin object that no longer lists that MimeType as a supported MimeType).


A MimeTypeArray object represents the MIME types explicitly supported by plugins supported by the user agent, each of which is represented by a MimeType object.

The MimeTypeArray objects created by a user agent must not be live. The set of MIME types represented by the objects must not change once an object is created, except when it is updated by the PluginArray object's refresh() method.

The supported property indices of a MimeTypeArray object are the numbers from zero to the number of MIME types explicitly supported by non-hidden plugins represented by the corresponding PluginArray object, if any. (This is a fingerprinting vector.)

The length attribute must return the number of MIME types explicitly supported by non-hidden plugins represented by the corresponding PluginArray object, if any. (This is a fingerprinting vector.)

The item() method of a MimeTypeArray object must return null if the argument is not one of the object's supported property indices, and otherwise must return the result of running the following steps, using the method's argument as index:

  1. Let list be the MimeType objects representing the MIME types explicitly supported by non-hidden plugins represented by the corresponding PluginArray object, if any.

  2. Sort list alphabetically by the type of each MimeType.

  3. Return the indexth entry in list.

It is important for privacy that the order of MIME types not leak additional information, e.g. the order in which plugins were installed.

The supported property names of a MimeTypeArray object are the values of the type attributes of all the MimeType objects represented by the MimeTypeArray object. (This is a fingerprinting vector.)

The namedItem() method of a MimeTypeArray object must return null if the argument is not one of the object's supported property names, and otherwise must return the MimeType object that has a type equal to the method's argument.


A Plugin object represents a plugin. It has several attributes to provide details about the plugin, and can be enumerated to obtain the list of MIME types that it explicitly supports.

The Plugin objects created by a user agent must not be live. The set of MIME types represented by the objects, and the values of the objects' attributes, must not change once an object is created, except when updated by the PluginArray object's refresh() method.

The reported MIME types for a Plugin object are the MIME types explicitly supported by the corresponding plugin when this object was last created or updated by PluginArray.refresh(), whichever happened most recently.

The supported property indices of a Plugin object are the numbers from zero to the number of reported MIME types. (This is a fingerprinting vector.)

The length attribute must return the number of reported MIME types. (This is a fingerprinting vector.)

The item() method of a Plugin object must return null if the argument is not one of the object's supported property indices, and otherwise must return the result of running the following steps, using the method's argument as index:

  1. Let list be the MimeType objects representing the reported MIME types.

  2. Sort list alphabetically by the type of each MimeType.

  3. Return the indexth entry in list.

It is important for privacy that the order of MIME types not leak additional information, e.g. the order in which plugins were installed.

The supported property names of a Plugin object are the values of the type attributes of the MimeType objects representing the reported MIME types. (This is a fingerprinting vector.)

The namedItem() method of a Plugin object must return null if the argument is not one of the object's supported property names, and otherwise must return the MimeType object that has a type equal to the method's argument.

The name attribute must return the plugin's name.

The description and filename attributes must return user-agent-defined (or, in all likelihood, plugin-defined) strings. In each case, the same string must be returned each time, except that the strings returned may change when the PluginArray.refresh() method updates the object.

If the values returned by the description or filename attributes vary between versions of a plugin, they can be used both as a fingerprinting vector and, even more importantly, as a trivial way to determine what security vulnerabilities a plugin (and thus a browser) may have. It is thus highly recommended that the description attribute just return the same value as the name attribute, and that the filename attribute return the empty string. (This is a fingerprinting vector.)


A MimeType object represents a MIME type that is, or was, explicitly supported by a plugin.

The MimeType objects created by a user agent must not be live. The values of the objects' attributes must not change once an object is created, except when updated by the PluginArray object's refresh() method.

The type attribute must return the valid MIME type with no parameters describing the MIME type.

The description and suffixes attributes must return user-agent-defined (or, in all likelihood, plugin-defined) strings. In each case, the same string must be returned each time, except that the strings returned may change when the PluginArray.refresh() method updates the object.

If the values returned by the description or suffixes attributes vary between versions of a plugin, they can be used both as a fingerprinting vector and, even more importantly, as a trivial way to determine what security vulnerabilities a plugin (and thus a browser) may have. It is thus highly recommended that the description attribute just return the same value as the type attribute, and that the suffixes attribute return the empty string. (This is a fingerprinting vector.)

Commas in the suffixes attribute are interpreted as separating subsequent filename extensions, as in "htm,html".

The enabledPlugin attribute must return the Plugin object that represents the plugin that explicitly supported the MIME type that this MimeType object represents when this object was last created or updated by PluginArray.refresh(), whichever happened most recently.


The navigator.javaEnabled() method must return true if the user agent supports a plugin that supports the MIME type "application/x-java-vm"; otherwise it must return false. (This is a fingerprinting vector.)

8.8 Images

[Exposed=(Window,Worker)]
interface ImageBitmap {
  readonly attribute unsigned long width;
  readonly attribute unsigned long height;
  void close();
};

typedef (CanvasImageSource or
         Blob or
         ImageData) ImageBitmapSource;

enum ImageOrientation { "none", "flipY" };
enum PremultiplyAlpha { "none", "premultiply", "default" };
enum ColorSpaceConversion { "none", "default" };
enum ResizeQuality { "pixelated", "low", "medium", "high" };

dictionary ImageBitmapOptions {
  ImageOrientation imageOrientation = "none";
  PremultiplyAlpha premultiplyAlpha = "default";
  ColorSpaceConversion colorSpaceConversion = "default";
  [EnforceRange] unsigned long resizeWidth;
  [EnforceRange] unsigned long resizeHeight;
  ResizeQuality resizeQuality = "low";
};

An ImageBitmap object represents a bitmap image that can be painted to a canvas without undue latency.

The exact judgement of what is undue latency of this is left up to the implementer, but in general if making use of the bitmap requires network I/O, or even local disk I/O, then the latency is probably undue; whereas if it only requires a blocking read from a GPU or system RAM, the latency is probably acceptable.

promise = self . createImageBitmap(image [, options ])
promise = self . createImageBitmap(image, sx, sy, sw, sh [, options ])

Takes image, which can be an img element, an SVG image element, a video element, a canvas element, a Blob object, an ImageData object, or another ImageBitmap object, and returns a promise that is resolved when a new ImageBitmap is created.

If no ImageBitmap object can be constructed, for example because the provided image data is not actually an image, then the promise is rejected instead.

If sx, sy, sw, and sh arguments are provided, the source image is cropped to the given pixels, with any pixels missing in the original replaced by transparent black. These coordinates are in the source image's pixel coordinate space, not in CSS pixels.

If options is provided, the ImageBitmap object's bitmap data is modified according to options. For example, if the premultiplyAlpha option is set to "premultiply", the bitmap data's color channels are premultiplied by its alpha channel.

Rejects the promise with an "InvalidStateError" DOMException if the source image is not in a valid state (e.g. an img element that hasn't loaded successfully, an ImageBitmap object whose [[Detached]] internal slot value is true, an ImageData object whose data attribute value's [[Detached]] internal slot value is true, or a Blob whose data cannot be interpreted as a bitmap image).

Rejects the promise with a "SecurityError" DOMException if the script is not allowed to access the image data of the source image (e.g. a video that is CORS-cross-origin, or a canvas being drawn on by a script in a worker from another origin).

imageBitmap . close()

Releases imageBitmap's underlying bitmap data.

imageBitmap . width

Returns the intrinsic width of the image, in CSS pixels.

imageBitmap . height

Returns the intrinsic height of the image, in CSS pixels.

An ImageBitmap object whose [[Detached]] internal slot value is false always has associated bitmap data, with a width and a height. However, it is possible for this data to be corrupted. If an ImageBitmap object's media data can be decoded without errors, it is said to be fully decodable.

An ImageBitmap object's bitmap has an origin-clean flag, which indicates whether the bitmap is tainted by content from a different origin. The flag is initially set to true and may be changed to false by the steps of createImageBitmap().

ImageBitmap objects are cloneable objects and transferable objects.

Each ImageBitmap object's [[Clone]](targetRealm, memory) internal method must run these steps:

  1. If this's [[Detached]] internal slot is true, then throw a "DataCloneError" DOMException.

  2. Return a new ImageBitmap object in targetRealm whose bitmap data is a copy of this's bitmap data, and whose origin-clean flag is set to the same value as this's origin-clean flag.

Each ImageBitmap object's [[Transfer]](targetRealm) internal method must run these steps:

  1. Let new be a new ImageBitmap object in targetRealm, pointing at the same underlying bitmap data as this.

  2. Set new's bitmap's origin-clean flag to the same values as this's bitmap's origin-clean flag.

  3. Set this's [[Detached]] internal slot value to true.

  4. Unset this's bitmap data.

  5. Return new.

An ImageBitmap object can be obtained from a variety of different objects, using the createImageBitmap() method. When invoked, the method must act as follows:

If image is an img element
If image is an SVG image element
  1. If either the sw or sh arguments are specified but zero, return a promise rejected with an "IndexSizeError" DOMException and abort these steps.

  2. If image is not completely available, then return a promise rejected with an "InvalidStateError" DOMException and abort these steps.

  3. If image's media data has no intrinsic dimensions (e.g. it's a vector graphic with no specified content size), and both or either of the resizeWidth and resizeHeight options are not specified, then return a promise rejected with an "InvalidStateError" DOMException and abort these steps.

  4. If image's media data has no intrinsic dimensions (e.g. it's a vector graphics with no specified content size), it should be rendered to a bitmap of the size specified by the resizeWidth and the resizeHeight options.

  5. If the sw and sh arguments are not specified and image's media data has both or either of its intrinsic width and intrinsic height values equal to 0, then return a promise rejected with an "InvalidStateError" DOMException and abort these steps.

  6. If the sh argument is not specified and image's media data has an intrinsic height of 0, then return a promise rejected with an "InvalidStateError" DOMException and abort these steps.

  7. Create a new ImageBitmap object.

  8. Let the ImageBitmap object's bitmap data be a copy of image's media data, cropped to the source rectangle with formatting. If this is an animated image, the ImageBitmap object's bitmap data must only be taken from the default image of the animation (the one that the format defines is to be used when animation is not supported or is disabled), or, if there is no such image, the first frame of the animation.

  9. If the origin of image's image is not the same origin as the origin specified by the entry settings object, then set the origin-clean flag of the ImageBitmap object's bitmap to false.

  10. Return a new promise, but continue running these steps in parallel.

  11. Resolve the promise with the new ImageBitmap object as the value.

If image is a video element
  1. If either the sw or sh arguments are specified but zero, return a promise rejected with an "IndexSizeError" DOMException and abort these steps.

  2. If the video element's networkState attribute is NETWORK_EMPTY, then return a promise rejected with an "InvalidStateError" DOMException and abort these steps.

  3. If the video element's readyState attribute is either HAVE_NOTHING or HAVE_METADATA, then return a promise rejected with an "InvalidStateError" DOMException and abort these steps.

  4. Create a new ImageBitmap object.

  5. Let the ImageBitmap object's bitmap data be a copy of the frame at the current playback position, at the media resource's intrinsic width and intrinsic height (i.e. after any aspect-ratio correction has been applied), cropped to the source rectangle with formatting.

  6. If the origin of the video element is not the same origin as the origin specified by the entry settings object, then set the origin-clean flag of the ImageBitmap object's bitmap to false.

  7. Return a new promise, but continue running these steps in parallel.

  8. Resolve the promise with the new ImageBitmap object as the value.

If image is a canvas element
  1. If either the sw or sh arguments are specified but zero, return a promise rejected with an "IndexSizeError" DOMException and abort these steps.

  2. If the canvas element's bitmap has either a horizontal dimension or a vertical dimension equal to zero, then return a promise rejected with an "InvalidStateError" DOMException and abort these steps.

  3. Create a new ImageBitmap object.

  4. Let the ImageBitmap object's bitmap data be a copy of the canvas element's bitmap data, cropped to the source rectangle with formatting.

  5. Set the origin-clean flag of the ImageBitmap object's bitmap to the same value as the origin-clean flag of the canvas element's bitmap.

  6. Return a new promise, but continue running these steps in parallel.

  7. Resolve the promise with the new ImageBitmap object as the value.

If image is a Blob object
  1. If either the sw or sh arguments are specified but zero, return a promise rejected with an "IndexSizeError" DOMException and abort these steps.

  2. If image is closed, then return a promise rejected with an "InvalidStateError" DOMException and abort these steps.

  3. Return a new promise, but continue running these steps in parallel.

  4. Read the Blob object's data. If an error occurs during reading of the object, then reject the promise with an "InvalidStateError" DOMException, and abort these steps.

  5. Apply the image sniffing rules to determine the file format of the image data, with MIME type of the Blob (as given by the Blob object's type attribute) giving the official type.

  6. If the image data is not in a supported image file format (e.g. it's not an image at all), or if the image data is corrupted in some fatal way such that the image dimensions cannot be obtained (e.g. a vector graphic with no intrinsic size), then reject the promise with an "InvalidStateError" DOMException, and abort these steps.

  7. Create a new ImageBitmap object.

  8. Let the ImageBitmap object's bitmap data be the image data read from the Blob object, cropped to the source rectangle with formatting. If this is an animated image, the ImageBitmap object's bitmap data must only be taken from the default image of the animation (the one that the format defines is to be used when animation is not supported or is disabled), or, if there is no such image, the first frame of the animation.

  9. Resolve the promise with the new ImageBitmap object as the value.

If image is an ImageData object
  1. If either the sw or sh arguments are specified but zero, return a promise rejected with an "IndexSizeError" DOMException and abort these steps.

  2. If the image object's data attribute value's [[Detached]] internal slot value is true, return a promise rejected with an "InvalidStateError" DOMException and abort these steps.

  3. Create a new ImageBitmap object.

  4. Let the ImageBitmap object's bitmap data be the image data given by the ImageData object, cropped to the source rectangle with formatting.

  5. Return a new promise, but continue running these steps in parallel.

  6. Resolve the promise with the new ImageBitmap object as the value.

If image is an ImageBitmap object
  1. If either the sw or sh arguments are specified but zero, return a promise rejected with an "IndexSizeError" DOMException and abort these steps.

  2. If image's [[Detached]] internal slot value is true, return a promise rejected with an "InvalidStateError" DOMException and abort these steps.

  3. Create a new ImageBitmap object.

  4. Let the ImageBitmap object's bitmap data be a copy of the image argument's bitmap data, cropped to the source rectangle with formatting.

  5. Set the origin-clean flag of the ImageBitmap object's bitmap to the same value as the origin-clean flag of the bitmap of the image argument.

  6. Return a new promise, but continue running these steps in parallel.

  7. Resolve the promise with the new ImageBitmap object as the value.

When the steps above require that the user agent crop bitmap data to the source rectangle with formatting, the user agent must run the following steps:

  1. Let input be the bitmap data being transformed.

  2. If either or both of resizeWidth and resizeHeight members of options are less than or equal to 0, then return a promise rejected with "InvalidStateError" DOMException and abort these steps.

  3. If sx, sy, sw and sh are specified, let sourceRectangle be a rectangle whose corners are the four points (sx, sy), (sx+sw, sy),(sx+sw, sy+sh), (sx,sy+sh). Otherwise let sourceRectangle be a rectangle whose corners are the four points (0,0), (width of input, 0), (width of input, height of input), (0, height of input).

    If either sw or sh are negative, then the top-left corner of this rectangle will be to the left or above the (sx, sy) point.

  4. Clip sourceRectangle to the dimensions of input.

  5. Let outputWidth be determined as follows:

    If the resizeWidth member of options is specified
    the value of the resizeWidth member of options
    If the resizeWidth member of options is not specified, but the resizeHeight member is specified
    the width of sourceRectangle, times the value of the resizeHeight member of options, divided by the height of sourceRectangle, rounded up to the nearest integer
    If neither resizeWidth nor resizeHeight are specified
    the width of sourceRectangle
  6. Let outputHeight be determined as follows:

    If the resizeHeight member of options is specified
    the value of the resizeHeight member of options
    If the resizeHeight member of options is not specified, but the resizeWidth member is specified
    the height of sourceRectangle, times the value of the resizeWidth member of options, divided by the width of sourceRectangle, rounded up to the nearest integer
    If neither resizeWidth nor resizeHeight are specified
    the height of sourceRectangle
  7. Place input on an infinite transparent black grid plane, positioned so that its top left corner is at the origin of the plane, with the x-coordinate increasing to the right, and the y-coordinate increasing down, and with each pixel in the input image data occupying a cell on the plane's grid.

  8. Let output be the rectangle on the plane denoted by sourceRectangle.

  9. Scale output to the size specified by outputWidth and outputHeight. The user agent should use the value of the resizeQuality option to guide the choice of scaling algorithm.

  10. If the value of the imageOrientation member of options is "flipY", output must be flipped vertically, disregarding any image orientation metadata of the source (such as EXIF metadata), if any. [EXIF]

    If the value is "none", no extra step is required.

  11. If image is an img element or a Blob object, let val be the value of the colorSpaceConversion member of options, and then run these substeps:

    1. If val is "default", the color space conversion behavior is implementation-specific, and should be chosen according to the color space that the implementation uses for drawing images onto the canvas.

    2. If val is "none", output must be decoded without performing any color space conversions. This means that the image decoding algorithm must ignore color profile metadata embedded in the source data as well as the display device color profile.

    The native color space of canvas is currently unspecified, but this is expected to change in the future.

  12. Let val be the value of premultiplyAlpha member of options, and then run these substeps:

    1. If val is "default", the alpha premultiplication behavior is implementation-specific, and should be chosen according to implementation deems optimal for drawing images onto the canvas.

    2. If val is "premultiply", the output that is not premultiplied by alpha must have its color components multiplied by alpha and that is premultiplied by alpha must be left untouched.

    3. If val is "none", the output that is not premultiplied by alpha must be left untouched and that is premultiplied by alpha must have its color components divided by alpha.

  13. Return output.

When the close() method is called, the user agent must run these steps:

  1. Set this ImageBitmap object's [[Detached]] internal slot value to true.

  2. Unset this ImageBitmap object's bitmap data.

The width attribute's getter must run these steps:

  1. If this ImageBitmap object's [[Detached]] internal slot's value is true, then return 0.

  2. Return this ImageBitmap object's width, in CSS pixels.

The height attribute's getter must run these steps:

  1. If this ImageBitmap object's [[Detached]] internal slot's value is true, then return 0.

  2. Return this ImageBitmap object's height, in CSS pixels.

The ResizeQuality enumeration is used to express a preference for the interpolation quality to use when scaling images.

The "pixelated" value indicates a preference to scale the image that maximizes the appearance. Scaling algorithms that "smooth" colors are acceptable, such as bilinear interpolation.

The "low" value indicates a preference for a low level of image interpolation quality. Low-quality image interpolation may be more computationally efficient than higher settings.

The "medium" value indicates a preference for a medium level of image interpolation quality.

The "high" value indicates a preference for a high level of image interpolation quality. High-quality image interpolation may be more computationally expensive than lower settings.

Bilinear scaling is an example of a relatively fast, lower-quality image-smoothing algorithm. Bicubic or Lanczos scaling are examples of image-scaling algorithms that produce higher-quality output. This specification does not mandate that specific interpolation algorithms be used unless the value is "pixelated".

Using this API, a sprite sheet can be precut and prepared:

var sprites = {};
function loadMySprites() {
  var image = new Image();
  image.src = 'mysprites.png';
  var resolver;
  var promise = new Promise(function (arg) { resolver = arg });
  image.onload = function () {
    resolver(Promise.all(
      createImageBitmap(image,  0,  0, 40, 40).then(function (image) { sprites.woman = image }),
      createImageBitmap(image, 40,  0, 40, 40).then(function (image) { sprites.man   = image }),
      createImageBitmap(image, 80,  0, 40, 40).then(function (image) { sprites.tree  = image }),
      createImageBitmap(image,  0, 40, 40, 40).then(function (image) { sprites.hut   = image }),
      createImageBitmap(image, 40, 40, 40, 40).then(function (image) { sprites.apple = image }),
      createImageBitmap(image, 80, 40, 40, 40).then(function (image) { sprites.snake = image }),
    ));
  };
  return promise;
}

function runDemo() {
  var canvas = document.querySelector('canvas#demo');
  var context = canvas.getContext('2d');
  context.drawImage(sprites.tree, 30, 10);
  context.drawImage(sprites.snake, 70, 10);
}

loadMySprites().then(runDemo);

8.9 Animation Frames

Support: requestanimationframeChrome for Android 56+Chrome 24+UC Browser for Android 11+iOS Safari 7.0+Firefox 23+IE 10+Samsung Internet 4+Opera Mini NoneAndroid Browser 4.4+Safari 6.1+Edge 12+Opera 15+

Source: caniuse.com

Each Document has a list of animation frame callbacks, which must be initially empty, and an animation frame callback identifier, which is a number which must initially be zero.

When the requestAnimationFrame() method is called, the user agent must run the following steps:

  1. Let document be this Window object's associated Document.

  2. Increment document's animation frame callback identifier by one.

  3. Append the method's argument to document's list of animation frame callbacks, associated with document's animation frame callback identifier's current value.

  4. Return document's animation frame callback identifier's current value.

When the cancelAnimationFrame() method is called, the user agent must run the following steps:

  1. Let document be this Window object's associated Document.

  2. Find the entry in document's list of animation frame callbacks that is associated with the value given by the method's argument.

  3. If there is such an entry, remove it from document's list of animation frame callbacks.

When the user agent is to run the animation frame callbacks for a Document doc with a timestamp now, it must run the following steps:

  1. Let callbacks be a list of the entries in doc's list of animation frame callbacks, in the order in which they were added to the list.

  2. Set doc's list of animation frame callbacks to the empty list.

  3. For each entry in callbacks, in order: invoke the callback, passing now as the only argument, and if an exception is thrown, report the exception. [WEBIDL]