1. 8 Web 应用 API
    1. 8.1 脚本
      1. 8.1.1 概述
      2. 8.1.2 启用和禁用脚本
      3. 8.1.3 处理模型
        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 Realm, 设置对象, 和全局对象
          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 与 JavaScript 任务队列的集成
          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(referencingScriptOrModule, specifier)
          2. 8.1.3.8.2 HostImportModuleDynamically(referencingScriptOrModule, specifier, promiseCapability)
          3. 8.1.3.8.3 HostGetImportMetaProperties(moduleRecord)
        9. 8.1.3.9 Integration with the JavaScript agent formalism
        10. 8.1.3.10 Integration with the JavaScript agent cluster formalism
        11. 8.1.3.11 Runtime script errors
          1. 8.1.3.11.1 文档中的运行时脚本错误
          2. 8.1.3.11.2 ErrorEvent 接口
        12. 8.1.3.12 Unhandled promise rejections
          1. 8.1.3.12.1 HostPromiseRejectionTracker(promise, operation)
          2. 8.1.3.12.2 PromiseRejectionEvent 接口
        13. 8.1.3.13 HostEnsureCanCompileStrings(callerRealm, calleeRealm)
      4. 8.1.4 事件循环
        1. 8.1.4.1 定义
        2. 8.1.4.2 Processing model
        3. 8.1.4.3 Generic task sources
        4. 8.1.4.4 Dealing with the event loop from other specifications
      5. 8.1.5 事件
        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

8 Web 应用 API

8.1 脚本

8.1.1 概述

有很多机制可以让作者提供的可执行代码在文档的上下文中运行。这些机制包括但不限于:

8.1.2 启用和禁用脚本

浏览环境 中下列条件都为真时, 脚本处于启用状态

浏览环境 中上述任何条件为假时, 脚本处于禁用状态 (例如当脚本没有 启用 时)。


如果一个节点 node节点文档 有一个 浏览上下文, 且该 浏览环境启用了脚本,那么 该节点 node启用了脚本

如果不存在这样的 浏览环境, 或者该 浏览环境脚本被禁用,那么该节点就 禁用了脚本.

8.1.3 处理模型

8.1.3.1 Definitions

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

A settings object

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

A record

Either a Script Record, for classic scripts; a Source Text Module Record, for module scripts; or null. In the former two cases, it represents a parsed script; null represents a failure parsing.

A parse error

A JavaScript value, which has meaning only if the record is null, indicating that the corresponding script source text could not be parsed.

An error to rethrow

A JavaScript value representing an error that will prevent evaluation from succeeding. It will be re-thrown by any attempts to run the script.

Since this exception value is provided by the JavaScript specification, we know that it is never null, so we use null to signal that no error has occurred.

Fetch options
A script fetch options, containing various options related to fetching this script or module scripts that it imports.
A base URL

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

A classic script is a type of script that has the following additional item:

A muted errors boolean

A boolean which, if true, means that error information will not be provided for errors in this script. This is used to mute errors for cross-origin scripts, since that can leak private information.

A module script is another type of script. It has no additional items.

The active script is determined by the following algorithm:

  1. Let record be GetActiveScriptOrModule().

  2. If record is null, return null.

  3. Return record.[[HostDefined]].


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

A URL record 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.

Specifications may define environment discarding steps for environments. The steps take an environment as input.

The environment discarding steps are run for only a select few environments: the ones that will never become execution ready because, for example, they failed to load.

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 Source Text Module Record's Evaluate 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(type, replace).

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.


Script fetch options is a struct with the following items:

cryptographic nonce

The cryptographic nonce metadata used for the initial fetch and for fetching any imported modules

integrity metadata

The integrity metadata used for the initial fetch

parser metadata

The parser metadata used for the initial fetch and for fetching any imported modules

credentials mode

The credentials mode used for the initial fetch (for module scripts) and for fetching any imported modules (for both module scripts and classic scripts)

referrer policy

The referrer policy used for the initial fetch and for fetching any imported modules

Recall that via the import() feature, classic scripts can import module scripts.

The default classic script fetch options are a script fetch options whose cryptographic nonce is the empty string, integrity metadata is the empty string, parser metadata is "not-parser-inserted", credentials mode is "omit", and referrer policy is the empty string.

Given a request request and a script fetch options options, we define:

set up the classic script request

Set request's cryptographic nonce metadata to options's cryptographic nonce, its integrity metadata to options's integrity metadata, its parser metadata to options's parser metadata, and its referrer policy to options's referrer policy.

set up the module script request

Set request's cryptographic nonce metadata to options's cryptographic nonce, its integrity metadata to options's integrity metadata, its parser metadata to options's parser metadata, its credentials mode to options's credentials mode, and its referrer policy to options's referrer policy.

For any given script fetch options options, the descendant script fetch options are a new script fetch options whose items all have the same values, except for the integrity metadata, which is instead the empty string.


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]


Now for the algorithms themselves.

To fetch a classic script given a url, a settings object, some options, 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.

  3. Set up the classic script request given request and options.

  4. 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.

  5. Let response be response's unsafe response.

  6. 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.

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

  8. 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.

  9. Let muted errors be true if response was CORS-cross-origin, and false otherwise.

  10. Let script be the result of creating a classic script given source text, settings object, response's url, options, and muted errors.

  11. 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, 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, script settings object, response's url, and the default classic script fetch options.

  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, 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.

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

  6. Let muted errors be true if response was CORS-cross-origin, and false otherwise.

  7. Let script be the result of creating a classic script given source text, settings object, response's url, the default classic script fetch options, and muted errors.

  8. Return script.

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

  1. Let visited set be « url ».

  2. Perform the internal module script graph fetching procedure given url, settings object, destination, options, settings object, visited set, "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.

  3. 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. Let visited set be « url ».

  2. Let options be a script fetch options whose cryptographic nonce is the empty string, integrity metadata is the empty string, parser metadata is "not-parser-inserted", credentials mode is credentials mode, and referrer policy is the empty string.

  3. Perform the internal module script graph fetching procedure given url, fetch client settings object, destination, options, module map settings object, visited set, "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.

  4. 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, some options, a module map settings object, a visited set, 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. Assert: visited set contains url.

  2. Fetch a single module script given url, fetch client settings object, destination, options, 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.

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

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

  5. If the top-level module fetch flag is set, fetch the descendants of and instantiate result given fetch client settings object, destination, and visited set. Otherwise, fetch the descendants of result given the same arguments.

  6. When the appropriate algorithm asynchronously completes with final result, asynchronously complete this algorithm with final result.

To fetch a single module script, given a url, a fetch client settings object, a destination, some options, 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, mode is "cors", referrer is referrer, and client is fetch client settings object.

  6. Set up the module script request given request and options.

  7. 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.

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

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

  10. Let module script be the result of creating a module script given source text, module map settings object, response's url, and options.

  11. 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 fetch client settings object, a destination, and a visited set, run these steps. The algorithm will asynchronously complete with either null (on failure) or with module script (on success).

  1. If module script's record is null, then asynchronously complete this algorithm with module script and abort these steps.

  2. Let record be module script's record.

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

  4. Let urls be a new empty list.

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

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

    2. Assert: url is never failure, because resolving a module specifier must have been previously successful with these same two arguments.

    3. If visited set does not contain url, then:

      1. Append url to urls.

      2. Append url to visited set.

  6. Let options be the descendant script fetch options for module script's fetch options.

  7. For each url in urls, perform the internal module script graph fetching procedure given url, fetch client settings object, destination, options, module script's settings object, visited set, 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.

    These invocations of the internal module script graph fetching procedure should be performed in parallel to each other.

    If any of the invocations of the internal module script graph fetching procedure asynchronously complete with null, asynchronously complete this algorithm with null, aborting these steps.

    Otherwise, wait until all of the internal module script graph fetching procedure invocations have asynchronously completed. Asynchronously complete this algorithm with module script.

To fetch the descendants of and instantiate a module script module script, given a fetch client settings object, a destination, and an optional visited set, run these steps. The algorithm will asynchronously complete with either null (on failure) or with module script (on success).

  1. If visited set was not given, let it be an empty set.

  2. Fetch the descendants of module script, given fetch client settings object, destination, and visited set.

  3. Return from this algorithm, and run the following steps when fetching the descendants of a module script asynchronously completes with result.

  4. If result is null, then asynchronously complete this algorithm with result.

    In this case, there was an error fetching one or more of the descendants. We will not attempt to instantiate.

  5. Let parse error be the result of finding the first parse error given result.

  6. If parse error is null, then:

    1. Let record be result's record.

    2. Perform record.Instantiate().

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

      If this throws an exception, set result's error to rethrow to that exception.

  7. Otherwise, set result's error to rethrow to parse error.

  8. Asynchronously complete this algorithm with result.

To find the first parse error given a root moduleScript and an optional discoveredSet:

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

  2. If discoveredSet was not given, let it be an empty set.

  3. Append moduleScript to discoveredSet.

  4. If moduleScript's record is null, then return moduleScript's parse error.

  5. Let childSpecifiers be the value of moduleScript's record's [[RequestedModules]] internal slot.

  6. Let childURLs be the list obtained by calling resolve a module specifier once for each item of childSpecifiers, given moduleScript's base URL and that item. (None of these will ever fail, as otherwise moduleScript would have been marked as itself having a parse error.)

  7. Let childModules be the list obtained by getting each value in moduleMap whose key is given by an item of childURLs.

  8. For each childModule of childModules:

    1. Assert: childModule is a module script (i.e., it is not "fetching" or null); by now all module scripts in the graph rooted at moduleScript will have successfully been fetched.

    2. If discoveredSet already contains childModule, continue.

    3. Let childParseError be the result of finding the first parse error given childModule and discoveredSet.

    4. If childParseError is not null, return childParseError.

  9. Return null.

8.1.3.3 Creating scripts

To create a classic script, given a JavaScript string source, an environment settings object settings, a URL baseURL, some script fetch options options, and an optional muted errors boolean:

  1. If muted errors was not provided, let it be false.

  2. If scripting is disabled for settings's responsible browsing context, then set source to the empty string.

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

  4. Set script's settings object to settings.

  5. Set script's base URL to baseURL.

  6. Set script's fetch options to options.

  7. Set script's muted errors to muted errors.

  8. Set script's parse error and error to rethrow to null.

  9. Let result be ParseScript(source, settings's Realm, script).

    Passing script as the last parameter here ensures result.[[HostDefined]] will be script.

  10. If result is a list of errors, then:

    1. Set script's parse error and its error to rethrow to result[0].

    2. Return script.

  11. Set script's record to result.

  12. Return script.

To create a module script, given a JavaScript string source, an environment settings object settings, a URL baseURL, and some script fetch options options:

  1. If scripting is disabled for settings's responsible browsing context, then set source to the empty string.

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

  3. Set script's settings object to settings.

  4. Set script's base URL to baseURL.

  5. Set script's fetch options to options.

  6. Set script's parse error and error to rethrow to null.

  7. Let result be ParseModule(source, settings's Realm, script).

    Passing script as the last parameter here ensures result.[[HostDefined]] will be script.

  8. If result is a list of errors, then:

    1. Set script's parse error to result[0].

    2. Return script.

  9. For each string requested of result.[[RequestedModules]]:

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

    2. If url is failure, then:

      1. Let error be a new TypeError exception.

      2. Set script's parse error to error.

      3. Return script.

    This step is essentially validating all of the requested module specifiers. We treat a module with unresolvable module specifiers the same as one that cannot be parsed; in both cases, a syntactic issue makes it impossible to ever contemplate instantiating the module later.

  10. Set script's record to result.

  11. Return script.

8.1.3.4 Calling scripts

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

  1. If rethrow errors is not given, let it be false.

  2. Let settings be the settings object of script.

  3. Check if we can run script with settings. If this returns "do not run" then return.

  4. Prepare to run script given settings.

  5. Let evaluationStatus be null.

  6. If script's error to rethrow is not null, then set evaluationStatus to Completion { [[Type]]: throw, [[Value]]: script's error to rethrow, [[Target]]: empty }.

  7. Otherwise, set evaluationStatus to ScriptEvaluation(script's record).

    If ScriptEvaluation does not complete because the user agent has aborted the running script, leave evaluationStatus as null.

  8. If evaluationStatus is an abrupt completion, then:

    1. If rethrow errors is true and script's muted errors is false, then:

      1. Clean up after running script with settings.

      2. Rethrow evaluationStatus.[[Value]].

    2. If rethrow errors is true and script's muted errors is true, then:

      1. Clean up after running script with settings.

      2. Throw a "NetworkError" DOMException.

    3. Otherwise, rethrow errors is false. Perform the following steps:

      1. Report the exception given by evaluationStatus.[[Value]] for script.

      2. Clean up after running script with settings.

      3. Return undefined.

  9. Clean up after running script with settings.

  10. If evaluationStatus is a normal completion, return evaluationStatus.[[Value]].

    This value is only ever used by the javascript: URL steps.

  11. If we've reached this point, evaluationStatus was left as null because the script was aborted prematurely during evaluation. Return undefined.

To run a module script given a module script script, with an optional rethrow errors boolean:

  1. If rethrow errors is not given, let it be false.

  2. Let settings be the settings object of script.

  3. Check if we can run script with settings. If this returns "do not run" then return.

  4. Prepare to run script given settings.

  5. Let evaluationStatus be null.

  6. If script's error to rethrow is not null, then set evaluationStatus to Completion { [[Type]]: throw, [[Value]]: script's error to rethrow, [[Target]]: empty }.

  7. Otherwise:

    1. Let record be script's record.

    2. Set evaluationStatus to record.Evaluate().

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

      If Evaluate fails to complete as a result of the user agent aborting the running script, then set evaluationStatus to Completion { [[Type]]: throw, [[Value]]: a new "QuotaExceededError" DOMException, [[Target]]: empty }.

  8. If evaluationStatus is an abrupt completion, then:

    1. If rethrow errors is true, rethrow the exception given by evaluationStatus.[[Value]].

    2. Otherwise, report the exception given by evaluationStatus.[[Value]] for 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".

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

  3. Return "run".

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

  1. 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. 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 Realm, 设置对象, 和全局对象

全局对象JavaScript realm 的 [[GlobalObject]] 字段的 JavaScript 对象。

本规范中,所有 JavaScript realm 都是使用 WindowWorkerGlobalScope 全局对象初始化 的。

JavaScript Realm全局对象,和 环境设置对象 之间,总是存在一个 1-1-1 映射:

创建新的 JavaScript realm, 可能同时还有创建全局对象或全局 this 绑定(或者两个都创建)的指示,需要执行以下步骤:

  1. 用提供的创建全局对象和全局 this 绑定的自定义参数执行 InitializeHostDefinedRealm()。

  2. realm execution context 执行 JavaScript 执行上下文

    这是指前面的步骤创建的 JavaScript 执行上下文

  3. JavaScript 执行上下文栈 移除 realm execution context

  4. 返回 realm execution context


本规范中定义算法步骤时,指出用哪个 JavaScript realm, (等价地,哪个 全局对象, 或哪个 环境设置对象)通常很重要。 通常有至少 4 种可能:

Entry
这对应于初始化当前执行动作的脚本:例如当用户代理调用作者代码时进入的函数或脚本。
Incumbent
这对应于栈上最近进入的作者提供的函数或脚本, 或者最初安排当前执行的回调的那个作者提供的函数或脚本。
Current
这对应于当前执行的函数对象,包括内置的用户代理函数 (从 当前 JavaScript realm 得到), 这些函数可能不是由 JavaScript 实现的。
Relevant
每个 平台对象 有一个 relevant Realm, 大概是创建它的 JavaScript realm。当编写算法时, relevant Realm 比较重要的 平台对象 是当前执行函数对象的 this 值。 有些情况下,还有其他的一些重要的 relevant Realms,比如参数对应的那些。

注意 entryincumbent,和 current 的概念可以在没有任何限定的情况下使用, 但 relevant 必须用于特定的 平台对象

考虑下面的页面,a.html 加载到了一个浏览器窗口中, b.html 加载到了 iframe 中, c.htmld.html 的代码省略了 (他们可以直接是空文档):

<!-- 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>

每个页面有它的 浏览上下文,因此也有它自己的 JavaScript realm全局对象环境设置对象

a.html 中的按钮按下时,会调用 print() 方法:

incumbententry 概念不应用于新的规范, 因为它们过于复杂且不够直观。我们正在致力于移除本平台上仍然存在的引用: incumbentissue #1430entryissue #1431

通常 Web 平台标准应该使用 relevant 概念, 对应于正在操作的对象(通常是当前方法的 this 值)。 这与 JavaScript 规范不匹配, 那里 current 通常被用作默认值 (例如在 Array.prototype.map 中确定应该使用哪个 JavaScript realmArray 构造函数来构造结果时)。 但是,这种不一致性深深植根于平台之中,我们不得不接受它。

注意在构造器中还没有 this 值,current 概念就是合适的默认值。

通常选择 relevant 的概念作为默认值 比 current 概念更好, 其中一个原因是它更适合创建永久的会返回多次的对象。例如 navigator.getBattery() 方法会在调用它的 Navigator 对象的 relevant Realm 中创建 Promise。 但这会有如下影响: [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>

如果 getBattery() 方法的算法中, 使用的是 current Realm,所有的结果会反转过来。 也就是说在 outer.html 中第一次在 inner.htmlNavigator 对象上调用 getBattery() 方法后, 会永久地存一个在 outer.htmlJavaScript realm 中创建的 Promise 对象, 在 hello() 中的这种调用,函数会返回一个 “错误” 的 Realm。 由于这是我们不希望发生的,该算法还是使用 relevant Realm, 给出上述注释中表示的合理结果。


本节剩余的部分正式定义了 entryincumbentcurrentrelevant 概念。

8.1.3.5.1 Entry

The process of calling scripts will push or pop realm execution contexts onto the JavaScript execution context stack, interspersed with other execution contexts.

With this in hand, we define the entry execution context to be the most recently pushed item in the JavaScript execution context stack that is a realm execution context. 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 object.

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

JavaScript 规范定义了 current Realm Record,简称为 "current Realm"。 [JAVASCRIPT]

那么 当前设置对象 就是 current Realm Record环境设置对象

类似地,当前全局对象 就是 current Realm Record全局对象

8.1.3.5.4 Relevant

平台对象相关设置对象 定义如下:

如果该对象是一个 全局对象
本规范中的每个 全局对象 创建时都会有一个 对应的 环境设置对象; 这就是它的 相关设置对象
其他情况

非全局 平台对象 o相关设置对象 是 相关的 全局对象o 关联的全局环境 的 全局对象的 环境设置对象

"关联的全局环境" 概念来自很久之前,甚至在现代 JavaScript 规范及其 realms 概念以前。我们期待 Web IDL 规范更新时,每个 平台对象 都有一个与之关联的 Realm, 这个定义可以更换那些术语。[JAVASCRIPT] [WEBIDL]

那么 平台对象相关 Realm 就是它的 相关设置对象Realm

类似地,平台对象相关全局对象 就是它的 相关设置对象全局对象

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 Source Text Module Record Evaluate invocations 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 与 JavaScript 任务队列的集成

JavaScript 规范定义了 JavaScript 任务和任务队列抽象, 以便指定某些不变量,以确定操作如何使用干净的 JavaScript 执行上下文堆栈 以特定顺序执行。然而截至撰写本文时,EnqueueJob 在其规范中的定义还不足以灵活地与作为宿主环境的 HTML 集成。[JAVASCRIPT]

这不完全正确,事实上利用算法的 "实现方定义" 部分的的自由性, 可以把算法扭曲为我们所用。但这样做的结果是用一堆间接的和变通的方式完全绕开任务队列基础设施。 虽然技术上符合实现方定义行为的边界,但我们不会走这条路,而是引入了下面的 对规范的有意违反

同样地,用户代理必须使用以下定义代替 JavaScript 规范中的定义。 这保证了由 JavaScript 规范入队的 Promise 任务能很好地集成到用户代理的 事件循环 中。

用户代理不得使用 JavaScript 规范中的 RunJobs 抽象操作。

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. Let active script be the active script.

  5. Assert: active script is not null, as jobs are only enqueued by the JavaScript specification while a script is active.

  6. Let script execution context be a new JavaScript execution context, with its Function field set to null, its Realm field set to active script's settings object's Realm, and its ScriptOrModule set to active script's record.

  7. 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 return.

    2. Prepare to run script with job settings.

      This affects the entry concept while the job runs.

    3. Prepare to run a callback with incumbent settings.

      This affects the incumbent concept while the job runs.

    4. Push script execution context onto the JavaScript execution context stack.

      This affects the active script while the job runs, in cases like Promise.resolve("...").then(eval) where there would otherwise be no active script since eval() is a built-in function that does not originate from any particular script.

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

    6. Pop script execution context from the JavaScript execution context stack.

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

    8. Clean up after running script with job settings.

    9. If result is an abrupt completion, then 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 URL records 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.mjs";
import "https://example.com/module.mjs#map-buster";
import "https://example.com/module.mjs?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.mjs";
import "https:example.com/module2.mjs";
import "https://///example.com\\module2.mjs";
import "https://example.com/foo/../module2.mjs";

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 URL base URL and a JavaScript string specifier, perform the following steps. It will return either a URL record 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.

    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 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(referencingScriptOrModule, specifier)

JavaScript contains an implementation-defined HostResolveImportedModule abstract operation, very slightly updated by the import() proposal. User agents must use the following implementation: [JAVASCRIPT] [JSIMPORT]

  1. Let referencing script be referencingScriptOrModule.[[HostDefined]].

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

  3. Let url be the result of resolving a module specifier given referencing script's base URL and specifier.

  4. Assert: url is never failure, because resolving a module specifier must have been previously successful with these same two arguments.

  5. Let resolved module script be moduleMap[url]. (This entry must exist for us to have gotten to this point.)

  6. Assert: resolved module script is a module script (i.e., is not null or "fetching").

  7. Assert: resolved module script's record is not null.

  8. Return resolved module script's record.

8.1.3.8.2 HostImportModuleDynamically(referencingScriptOrModule, specifier, promiseCapability)

The import() proposal contains an implementation-defined HostImportModuleDynamically abstract operation. User agents must use the following implementation: [JSIMPORT]

  1. Let referencing script be referencingScriptOrModule.[[HostDefined]].

  2. Run the following steps in parallel:

    1. Let url be the result of resolving a module specifier given referencing script's base URL and specifier.

    2. If url is failure, then:

      1. Let completion be Completion { [[Type]]: throw, [[Value]]: a new TypeError, [[Target]]: empty }.

      2. Perform FinishDynamicImport(referencingScriptOrModule, specifier, promiseCapability, completion).

      3. Return.

    3. Let options be the descendant script fetch options for referencing script's fetch options.

    4. Fetch a module script graph given url, referencing script's settings object, "script", and options. Wait until the algorithm asynchronously completes with result.

    5. If result is null, then:

      1. Let completion be Completion { [[Type]]: throw, [[Value]]: a new TypeError, [[Target]]: empty }.

      2. Perform FinishDynamicImport(referencingScriptOrModule, specifier, promiseCapability, completion).

      3. Return.

    6. Run the module script result, with the rethrow errors boolean set to true.

    7. If running the module script throws an exception, then perform FinishDynamicImport(referencingScriptOrModule, specifier, promiseCapability, the thrown exception completion).

    8. Otherwise, perform FinishDynamicImport(referencingScriptOrModule, specifier, promiseCapability, NormalCompletion(undefined)).

  3. Return undefined.

8.1.3.8.3 HostGetImportMetaProperties(moduleRecord)

The import.meta proposal contains an implementation-defined HostGetImportMetaProperties abstract operation. User agents must use the following implementation: [JSIMPORTMETA]

  1. Let module script be moduleRecord.[[HostDefined]].

  2. Let urlString be module script's base URL, serialized.

  3. Return « Record { [[Key]]: "url", [[Value]]: urlString } ».

8.1.3.9 Integration with the JavaScript agent formalism

JavaScript defines the concept of an agent. This section gives the mapping of that language-level concept on to the web platform.

JavaScript is expected to define agents in more detail; in particular that they hold a set of realms: tc39/ecma262 issue #882.

Conceptually, the agent concept is an architecture-independent, idealized "thread" in which JavaScript code runs. Such code can involve multiple globals/realms that can synchronously access each other, and thus need to run in a single execution thread.

Until such a time that this standard has a better handle on lifetimes, it defines five types of agents that user agents must allocate at the appropriate time.

In the future, this standard hopes to define exactly when agents and agent clusters are created.

Similar-origin window agent

An agent whose [[CanBlock]] is false and whose set of realms consists of all realms of Window objects whose relevant settings object's responsible browsing context is in the same unit of related similar-origin browsing contexts.

Two Window objects that are same origin can be in different similar-origin window agents, for instance if they are each in their own unit of related similar-origin browsing contexts.

Dedicated worker agent

An agent whose [[CanBlock]] is true and whose set of realms consists of a single DedicatedWorkerGlobalScope object's Realm.

Shared worker agent

An agent whose [[CanBlock]] is true and whose set of realms consists a single SharedWorkerGlobalScope object's Realm.

Service worker agent

An agent whose [[CanBlock]] is false and whose set of realms consists of a single ServiceWorkerGlobalScope object's Realm.

Worklet agent

An agent whose [[CanBlock]] is false and whose set of realms consists of a single WorkletGlobalScope object's Realm.

Although a given worklet can have multiple realms, each such realm needs its own agent, as each realm can be executing code independently and at the same time as the others.

8.1.3.10 Integration with the JavaScript agent cluster formalism

JavaScript also defines the concept of an agent cluster, which this standard maps to the web platform using the can share memory with equivalence relation detailed below. On the web platform, an agent cluster consists of all agents in the same equivalence class with respect to the can share memory with equivalence relation.

The agent cluster concept is crucial for defining the JavaScript memory model, and in particular among which agents the backing data of SharedArrayBuffer objects can be shared.

Conceptually, the agent cluster concept is an architecture-independent, idealized "process boundary" that groups together multiple "threads" (agents). The agent clusters defined by the specification are generally more restrictive than the actual process boundaries implemented in user agents. By enforcing these idealized divisions at the specification level, we ensure that web developers see interoperable behavior with regard to shared memory, even in the face of varying and changing user agent process models.

A similar-origin window agent, dedicated worker agent, shared worker agent, or service worker agent, agent, can share memory with any dedicated worker agent whose single realm's global object's owner set contains an item whose relevant Realm belongs to agent.

"Item" is used above as an owner set can contain Document objects.

A worklet agent … currently worklets have no clearly defined owner, see: w3c/css-houdini-drafts issue #224.

In addition, any agent A can share memory with:

The following pairs of global objects are each within the same agent cluster, and thus can use SharedArrayBuffer instances to share memory with each other:

The following pairs of global objects are not within the same agent cluster, and thus cannot share memory:

8.1.3.11 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 return; 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's muted errors is true, 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.11.1 文档中的运行时脚本错误

当用户代理要 报告异常 E 时, 必须带着包含脚本的资源中出问题的位置(行号和列号), 使用由脚本的 设置对象 指定的 全局对象 作为目标, 为相关的 脚本 报告错误。 如果在这之后这个错误仍然 未被处理, 那么这个错误可以报告给开发控制台。

8.1.3.11.2 ErrorEvent 接口
[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;
};

message 属性必须返回 它初始化的值。它表示错误消息。

The filename 属性必须返回 它初始化的值。它表示最初发生错误的脚本的 URL

The lineno 属性必须返回 它初始化的值。它表示脚本中错误发生的行号。

The colno 属性必须返回 它初始化的值。它表示脚本中错误发生的列号。

The error 属性必须返回 它初始化的值。合适的时候,它设为表示错误的对象(例如未捕获 DOM 异常中的异常对象)。

8.1.3.12 Unhandled promise rejections

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

Support: unhandledrejectionChrome for Android 67+Chrome 49+iOS Safari NoneUC Browser for Android 11.8+Firefox NoneIE NoneOpera Mini NoneSafari 11+Edge NoneSamsung Internet 5+Android Browser 67+Opera 36+

Source: caniuse.com

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, return.

  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.12.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's muted errors is true, 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, then remove promise from that list and return.

    2. If settings object's outstanding rejected promises weak set does not contain promise, then return.

    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.12.2 PromiseRejectionEvent 接口
[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;
};

promise 属性必须返回它初始化的值,表示这个通知的 Promise。

reason 属性必须返回它初始化的值,表示这个 Promise 的拒绝原因。

8.1.3.13 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 事件循环

8.1.4.1 定义

为了协调事件、用户交互、脚本、渲染、网络等,用户代理必须使用这一小节描述的 事件循环。 共有两种事件循环:用于 浏览上下文的, 以及用于 worker 的。

每个用户代理必须有至少一个 浏览上下文 事件循环, 每个 相关类似域名浏览上下文单位 最多一个。

一个 相关浏览上下文单位 有多于一个 事件循环 时,当 那个组中的一个 浏览上下文 导航 时就会很复杂。因为它会从一个 相关类似域名浏览上下文单元 切换到另一个。本规范目前没有描述如何处理这些复杂性。

浏览上下文 事件循环 总是有至少一个 浏览上下文。如果这样的 事件循环浏览上下文 消失了,那么这个 事件循环 也会消失。 浏览上下文 总是有一个 事件循环 来协调它的活动。

Worker 事件循环 是类似的: 每个 Worker 有一个 事件循环, 且 Worker 处理模型 管理着 事件循环 的生命期。


一个 事件循环 有一个或更多 任务队列。一个 任务队列 是一个 任务 的有序列表, 这些任务是负责以下工作的算法:

事件

在特定的 EventTarget 上派发一个 Event 对象, 通常由专门的任务完成。

不是所有事件都是由 任务队列 派发的, 很多是在其他任务执行过程中派发的。

解析

HTML 解析器 标记化一个或更多字节, 然后处理结果标记。这通常是一个任务。

回调

调用一个回调通常是由专用任务来完成的。

使用资源

当一个算法 获取 一个资源时,如果获取发生在一个非阻塞的情况, 那么一旦某个或全部资源可用,对资源的处理由一个任务来执行。

对 DOM 操作作出反应

有些元素在 DOM 操作时会触发一些任务,例如当元素 插入到文档中 时。

浏览环境 事件循环 中, 每个 任务 与一个 Document 关联; 如果任务在一个元素的上下文入队,那么它就是这个元素的 节点文档; 如果任务在一个 浏览环境 的上下文入队, 那么它就是 浏览环境 在任务入队时的 活跃文档; 如果该任务是由(或为了)脚本 入队的,那么该文档就是脚本的 设置对象 指定的 负责文档

任务 针对特定的 事件循环: 即为 task 的关联 Documentworker 处理 任务事件循环

当用户代理要 入队一个任务 时,它必须把给定的任务添加到 相关 事件循环 的其中一个 任务队列 里面。

每个 任务 都定义为来自特定的 任务源。 来自特定 任务源 和指向特定的 事件循环 的的所有任务(例如,由一个 Document 的定时器生成的回调、Document 上鼠标移动触发的事件、 为 Document 的解析器入队的任务)必须总是被添加到同一个 任务队列, 但来自不同 任务源任务 可以放在不同的 任务队列 中。

例如,一个用户代理可以有一个 任务队列 处理鼠标和键盘事件 (用户交互任务源),另一个来处理其他的。 这样用户代理可以给键盘和鼠标事件比其他任务多 3/4 的处理时间,保证接口响应但又不让其他任务队列饥饿, 并且永远不处理来自任何 任务源 的乱序的事件。

每个 事件循环 有一个 当前执行任务。 初始化为 null,它用来处理重新进入的情况。 每个 事件循环 还有一个 执行一个 microtask 检查点 标志, 初始必须设为 false。它用来防止重新进入 microtask 检查点 算法的调用。

8.1.4.2 Processing model

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

  1. Let oldestTask be 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 oldestTask.

  3. Run oldestTask.

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

  5. Remove oldestTask 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 current high resolution time. [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, update animations and send events for that Document, passing in now as the timestamp. [WEBANIMATIONS]

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

    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.


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. Set the performing a microtask checkpoint flag to true.

  2. While the event loop's microtask queue is not empty:

    1. Let oldestMicrotask be the oldest microtask on the event loop's microtask queue.

    2. Set the event loop's currently running task to oldestMicrotask.

    3. Run oldestMicrotask.

      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.

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

    5. Remove oldestMicrotask from the microtask queue.

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

  4. Cleanup Indexed Database transactions.

  5. Set the performing a microtask checkpoint flag to 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.4.4 Dealing with the event loop from other specifications

Writing specifications that correctly interact with the event loop can be tricky. This is compounded by how this specification uses concurrency-model-independent terminology, so we say things like "event loop" and "in parallel" instead of using more familiar model-specific terms like "main thread" or "on a background thread".

By default, specification text generally runs on the event loop. This falls out from the formal event loop processing model, in that you can eventually trace most algorithms back to a task queued there.

The algorithm steps for any JavaScript method will be invoked by author code calling that method. And author code can only be run via queued tasks, usually originating somewhere in the script processing model.

From this starting point, the overriding guideline is that any work a specification needs to perform that would otherwise block the event loop must instead be performed in parallel with it. This includes (but is not limited to):

The next complication is that, in algorithm sections that are in parallel, you must not create or manipulate objects associated to a specific JavaScript realm, global, or environment settings object. (Stated in more familiar terms, you must not directly access main-thread artifacts from a background thread.) Doing so would create data races observable to JavaScript code, since after all, your algorithm steps are running in parallel to the JavaScript code.

You can, however, manipulate specification-level data structures and values from the WHATWG Infra Standard, as those are realm-agnostic. They are never directly exposed to JavaScript without a specific conversion taking place (often via Web IDL). [INFRA] [WEBIDL]

To affect the world of observable JavaScript objects, then, you must queue a task to perform any such manipulations. This ensures your steps are properly interleaved with respect to other things happening on the event loop. Furthermore, you must choose a task source when queueing a task; this governs the relative order of your steps versus others. If you are unsure which task source to use, pick one of the generic task sources that sounds most applicable.

Most invocations of queue a task implicitly use "the relevant event loop", i.e., the one that is obvious from context. That is because it is very rare for algorithms to be invoked in contexts involving multiple event loops. (Unlike contexts involving multiple global objects, which happen all the time!) So unless you are writing a specification which, e.g., deals with manipulating workers, you can omit this argument when queueing a task.

Putting this all together, we can provide a template for a typical algorithm that needs to do work asynchronously:

  1. Do any synchronous setup work, while still on the event loop. This may include converting realm-specific JavaScript values into realm-agnostic specification-level values.

  2. Perform a set of potentially-expensive steps in parallel, operating entirely on realm-agnostic values, and producing a realm-agnostic result.

  3. Queue a task, on a specified task source, to convert the realm-agnostic result back into observable effects on the observable world of JavaScript objects on the event loop.

The following is an algorithm that "encrypts" a passed-in list of scalar value strings input, after parsing them as URLs:

  1. Let urls be an empty list.

  2. For each string of input:

    1. Let parsed be the result of parsing string relative to the current settings object.

    2. If parsed is failure, return a promise rejected with a "SyntaxError" DOMException.

    3. Let serialized be the result of applying the URL serializer to parsed.

    4. Append serialized to urls.

  3. Let realm be the current Realm Record.

  4. Let p be a new promise.

  5. Run the following steps in parallel:

    1. Let encryptedURLs be an empty list.

    2. For each url of urls:

      1. Wait 100 milliseconds, so that people think we're doing heavy-duty encryption.

      2. Let encrypted be a new JavaScript string derived from url, whose nth code unit is equal to url's nth code unit plus 13.

      3. Append encrypted to encryptedURLs.

    3. Queue a task, on the networking task source, to perform the following steps:

      1. Let array be the result of converting encryptedURLs to a JavaScript array, in realm.

      2. Resolve p with array.

  6. Return p.

Here are several things to notice about this algorithm:

(On these last two points, see also w3ctag/promises-guide#52, heycam/webidl#135, and heycam/webidl#371, where we are still mulling over the subtleties of the above promise-resolution pattern.)

Another thing to note is that, in the event this algorithm was called from a Web IDL-specified operation taking a sequence<USVString>, there was an automatic conversion from realm-specific JavaScript objects provided by the author as input, into the realm-agnostic sequence<USVString> Web IDL type, which we then treat as a list of scalar value strings. So depending on how your specification is structured, there may be other implicit steps happening on the main event loop that play a part in this whole process of getting you ready to go in parallel.

8.1.5 事件

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 return. [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 EventTarget object T is first set to a non-null value, then:

  1. Let callback be 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.

  2. Let listener be a new event listener whose type is the event handler event type corresponding to H and callback is callback.

    To be clear, an event listener is different from an EventListener.

  3. Add an event listener with T and listener.

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 return.

  3. Let special error event handling be true if E is an ErrorEvent object, E's type is error, and E's currentTarget implements the WindowOrWorkerGlobalScope mixin. Otherwise, let special error event handling be false.

  4. Process the Event object E as follows:

    If special error event handling is true

    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]

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

  5. Process return value as follows:

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

    In this case, the event handler IDL attribute's type will be OnBeforeUnloadEventHandler, so return value will have been coerced into either 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.

    If special error event handling is true

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

    Otherwise

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

    If we've gotten to this "Otherwise" clause because E's type is beforeunload but E is not a BeforeUnloadEvent object, then return value will never be false, since in such cases return value will have been coerced into either null or a DOMString.


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.

There are two exceptions in the platform, for historical reasons:

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;
window.onerror = (message, source, lineno, colno, error) => { … };

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
onsecuritypolicyviolation securitypolicyviolation
onseeked seeked
onseeking seeking
onselect select
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
onmessageerror messageerror
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
interface mixin 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 onsecuritypolicyviolation;
  attribute EventHandler onseeked;
  attribute EventHandler onseeking;
  attribute EventHandler onselect;
  attribute EventHandler onstalled;
  attribute EventHandler onsubmit;
  attribute EventHandler onsuspend;
  attribute EventHandler ontimeupdate;
  attribute EventHandler ontoggle;
  attribute EventHandler onvolumechange;
  attribute EventHandler onwaiting;
};

interface mixin WindowEventHandlers {
  attribute EventHandler onafterprint;
  attribute EventHandler onbeforeprint;
  attribute OnBeforeUnloadEventHandler onbeforeunload;
  attribute EventHandler onhashchange;
  attribute EventHandler onlanguagechange;
  attribute EventHandler onmessage;
  attribute EventHandler onmessageerror;
  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;
};

interface mixin 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. Set event's composed flag.

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

  6. 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).

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

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

  9. 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 mixin WindowOrWorkerGlobalScope { … }; along with an appropriate reference.

typedef (DOMString or Function) TimerHandler;

interface mixin WindowOrWorkerGlobalScope {
  [Replaceable] readonly attribute USVString origin;

  // base64 utility methods
  DOMString btoa(DOMString data);
  ByteString 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 includes WindowOrWorkerGlobalScope;
WorkerGlobalScope includes 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 67+Chrome 4+iOS Safari 3.2+UC Browser for Android 11.8+Firefox 2+IE 10+Opera Mini all+Safari 3.1+Edge 12+Samsung Internet 4+Android Browser 2.1+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 byte sequence whose nth byte is the eight-bit representation of the nth code point of data, and then must apply forgiving-base64 encode to that byte sequence and return the result.

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

  1. Let decodedData be the result of running forgiving-base64 decode on data.

  2. If decodedData is failure, then throw an "InvalidCharacterError" DOMException.

  3. Return decodedData.