HTML Standard

WHATWG

HTML

Living Standard — Last Updated

8

Web application APIs

8.1

Scripting

8.1.1

Introduction

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

  • Processing of script elements.
  • Navigating to javascript: URLs.
  • Event handlers, whether registered through the DOM using addEventListener(), by explicit event handler content attributes, by
    event handler IDL attributes, or otherwise.
  • Processing of technologies like SVG that have their own scripting features.

8.1.2

Agents and agent clusters

8.1.2.1

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.

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 needs to run in a single execution thread.

Two Window objects having the same agent does not indicate
they can directly access all objects created in each other’s realms. They would have to be
same origin-domain; see IsPlatformObjectSameOrigin.

The following types of agents exist on the web platform:

Only shared and dedicated worker agents allow the use of JavaScript Atomics APIs to
potentially block.

To create an agent, given a boolean canBlock:

  1. Let signifier be a new unique internal value.

  2. Let candidateExecution be a new .

  3. Let agent be a new agent whose [[CanBlock]] is
    canBlock, [[Signifier]] is signifier, [[CandidateExecution]] is
    candidateExecution, and [[IsLockFree1]], [[IsLockFree2]], and [[LittleEndian]] are set
    at the implementation’s discretion.

  4. Set agent’s event loop to a new
    event loop.

  5. Return agent.

The relevant agent for a platform object
platformObject is platformObject’s relevant realm’s agent. This pointer is not yet defined in the JavaScript specification; see tc39/ecma262#1357.

The agent equivalent of the current realm is the surrounding
agent.

8.1.2.2

Integration with the JavaScript agent cluster formalism

JavaScript also defines the concept of an agent cluster, which this standard maps
to the web platform by placing agents appropriately when they are created using the
obtain a similar-origin window agent or
obtain a worker/worklet agent
algorithms.

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.

An agent cluster has an associated cross-origin isolation mode, which is a
cross-origin isolation mode. It is initially “none“.

An agent cluster has an associated is origin-keyed (a boolean), which
is initially false.

The following defines the allocation of the agent clusters
of similar-origin window agents.

An agent cluster key is a site or tuple origin. Without web developer action to achieve origin-keyed agent clusters, it will be a
site.

An equivalent formulation is that an agent cluster key can be a
scheme-and-host or an origin.

To obtain a similar-origin window agent,
given an origin origin, a browsing context group
group, and a boolean requestsOAC, run these steps:

This means that there is only one similar-origin window agent per
browsing context agent cluster. (However, dedicated
worker and worklet agents might be in the same
cluster.)

The following defines the allocation of the agent clusters
of all other types of agents.

To obtain a worker/worklet agent, given an
environment settings object or null outside settings, a boolean
isTopLevel, and a boolean canBlock, run these steps:

  1. Let agentCluster be null.

  2. If isTopLevel is true, then:

    1. Set agentCluster to a new agent cluster.

    2. Set agentCluster’s is origin-keyed to true.

      These workers can be considered to be origin-keyed. However, this is not
      exposed through any APIs (in the way that originAgentCluster exposes the origin-keyedness for
      windows).

  3. Otherwise:

    1. Assert: outside settings is not null.

    2. Let ownerAgent be outside settings’s realm’s agent.

    3. Set agentCluster to the agent cluster which contains
      ownerAgent.

  4. Let agent be the result of creating an
    agent given canBlock.

  5. Add agent to agentCluster.

  6. Return agent.

To obtain a dedicated/shared worker agent, given an environment settings
object outside settings and a boolean isShared, return the result of
obtaining a worker/worklet agent given outside settings,
isShared, and true.

To obtain a worklet agent, given an environment settings object
outside settings, return the result of obtaining a worker/worklet agent
given outside settings, false, and false.

To obtain a service worker agent, return the result of obtaining a
worker/worklet agent given null, true, and false.

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:

  • A Window object and a dedicated worker that it created.
  • A worker (of any type) and a dedicated worker it created.
  • A Window object A and the Window object of an
    iframe element that A created that could be same
    origin-domain with A.
  • A Window object and a same origin-domain Window
    object that opened it.
  • A Window object and a worklet that it created.

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

  • A Window object and a shared worker it created.
  • A worker (of any type) and a shared worker it created.
  • A Window object and a service worker it created.
  • A Window object and the Window object of an
    iframe element that A created that cannot be same
    origin-domain with A.
  • Any two Window objects with no opener or ancestor relationship. This holds
    even if the two Window objects are same origin.

8.1.3

Realms and their counterparts

The JavaScript specification introduces the realm concept, representing a global
environment in which script is run. Each realm comes with an implementation-defined
global object; much of this specification is devoted to defining that global object
and its properties.

For web specifications, it is often useful to associate values or algorithms with a
realm/global object pair. When the values are specific to a particular type of realm, they are
associated directly with the global object in question, e.g., in the definition of the
Window or WorkerGlobalScope interfaces. When the values have utility
across multiple realms, we use the environment settings object concept.

Finally, in some cases it is necessary to track associated values before a
realm/global object/environment settings object even comes into existence (for example, during
navigation). These values are tracked in the
environment concept.

8.1.3.1

Environments

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

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.

8.1.3.2

Environment settings objects

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

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.

An environment settings object’s responsible event loop is its global
object’s relevant agent’s event
loop.

8.1.3.3

Realms, settings objects, and global objects

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

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

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

To create a new
realm in an agent agent, optionally with instructions to create a
global object or a global this binding (or both), the following steps are taken:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  • The entry realm is that of a.html.

  • The incumbent realm is that of b.html.

  • The current realm is that of c.html (since it is the
    print() method from c.html whose code is
    running).

  • The relevant realm of the object on which
    the print() method is being called is that of d.html.

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

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

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

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

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

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

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

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

8.1.3.3.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.3.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 HostEnqueuePromiseJob 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:

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

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:

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:

8.1.3.3.3

Current

The JavaScript specification defines the current realm, also known as the “current
Realm Record”. [JAVASCRIPT]

Then, the current settings object is the environment settings object of the current
realm.

Similarly, the current global object is the global object of the current realm.

8.1.3.3.4

Relevant

The relevant realm for a platform
object is the value of its [[Realm]]
field.

Then, the relevant settings object for a platform object
o is the environment settings
object of the relevant realm for
o.

Similarly, the relevant global object for a
platform object o is the global
object of the relevant realm for
o.

8.1.3.4

Enabling and disabling scripting

Scripting is enabled for
an environment settings object settings when all of the following
conditions are true:

Scripting is disabled
for an environment settings object when scripting is not enabled for it, i.e., when any of the above conditions
are false.

Scripting is enabled for a node node if
node’s node document’s browsing
context is non-null, and scripting is
enabled for node’s relevant settings object.

Scripting is disabled for a node when scripting is not
enabled, i.e., when its node document’s browsing context is null or when scripting is disabled for its relevant settings
object.

8.1.3.5

Secure contexts

An environment environment is a secure context if the following
algorithm returns true:

An environment is a non-secure context if it is not a
secure context.

8.1.4

Script processing
model

8.1.4.1

Scripts

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

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.

Module scripts can be classified into three types:

As CSS stylesheets and JSON documents do not import dependent modules, and do not
throw exceptions on evaluation, the fetch
options and base URL of CSS module scripts and JSON module
scripts and are always null.

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

The active script concept is so far only used by the
import() feature, to determine the base
URL to use for resolving relative module specifiers.

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

render-blocking

The boolean value of render-blocking
used for the initial fetch and for fetching any imported modules. Unless otherwise stated, its
value is false.

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 “same-origin“, and referrer policy is the empty
string.

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

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.

Several of the below algorithms can be customized with a perform the fetch
hook algorithm, which takes a request, a boolean isTopLevel, and a processCustomFetchResponse
algorithm. It runs processCustomFetchResponse with a response and either null (on failure) or a byte
sequence containing the response body. isTopLevel will be true for all classic
script fetches, and for the initial fetch when fetching an external module script graph, fetching a module worker script graph, or fetching an import() module script graph, but false for the fetches
resulting from import statements encountered throughout the graph.

By default, not supplying a perform the fetch
hook 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, a character
encoding, and an onComplete algorithm, run these steps. onComplete
must be an algorithm accepting null (on failure) or a classic script (on
success).

To fetch a classic worker script given a url, a fetch client
settings object, a destination, a script settings object, an
onComplete algorithm, and an optional perform the fetch hook performFetch, run
these steps. onComplete must be an algorithm accepting null (on failure) or a
classic script (on success).

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

To fetch an external module script graph
given a url, a settings object, some options, and an
onComplete algorithm, run these steps. onComplete must be an algorithm
accepting null (on failure) or a module script (on success).

  1. Disallow further import maps given settings object.

  2. Fetch a single module script given url, settings object,
    script“, options, settings object, “client“, true, and with the following steps given result:

    1. If result is null, run onComplete given null, and abort these
      steps.

    2. Let visited set be « (url, “javascript“)
      ».

    3. Fetch the descendants of
      and link result given settings object, “script“, visited set, and onComplete.

To fetch an import() module script graph given a moduleRequest, a
script, a settings object, some options, and an
onComplete algorithm, run these steps. onComplete must be an algorithm
accepting null (on failure) or a module script (on success).

To fetch a modulepreload module script graph given a url, a
destination, a settings object, some options, and an
onComplete algorithm, run these steps. onComplete must be an algorithm
accepting null (on failure) or a module script (on success).

  1. Disallow further import maps given settings object.

  2. Fetch a single module script given url, settings
    object, destination, options, settings object, “client“, true, and with the
    following steps given result:

    1. Run onComplete given result.

    2. If result is not null, optionally perform the following steps:

      1. Let visited set be « (url, “javascript“)
        ».

      2. Fetch the
        descendants of and link result given settings object,
        destination, visited set, and with an empty algorithm.

      Generally, performing these steps will be beneficial for performance, as it
      allows pre-loading the modules that will invariably be requested later, via algorithms such as
      fetch an external module script graph that fetch the entire graph. However, user
      agents might wish to skip them in bandwidth-constrained situations, or situations where the
      relevant fetches are already in flight.

To fetch an inline module script graph given a source text, base
URL, settings object, options, and an onComplete algorithm,
run these steps. onComplete must be an algorithm accepting null (on failure) or a
module script (on success).

  1. Disallow further import maps given settings object.

  2. Let script be the result of creating a JavaScript module script
    using source text, settings object, base URL, and
    options.

  3. If script is null, run onComplete given null, and return.

  4. Let visited set be an empty set.

  5. Fetch the
    descendants of and link script, given settings object, the
    destination “script“, visited set, and
    onComplete.

To fetch a module worker script graph
given a url, a fetch client settings object, a destination, a
credentials mode, a module map settings object, and an onComplete
algorithm, fetch a worklet/module worker script graph given url,
fetch client settings object, destination, credentials mode,
module map settings object, and onComplete.

To fetch a worklet script graph given a url, a fetch client settings
object, a destination, a credentials mode, a module map settings
object, a moduleResponsesMap, and an onComplete algorithm, fetch
a worklet/module worker script graph given url, fetch client settings
object, destination, credentials mode, module map settings
object, onComplete, and the following perform the fetch hook given request and
processCustomFetchResponse:

  1. Let requestURL be request’s URL.

  2. If moduleResponsesMap[requestURL] 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 moduleResponsesMap[requestURL] exists, then:

    1. Let cached be moduleResponsesMap[requestURL].

    2. Run processCustomFetchResponse with cached[0] and
      cached[1].

    3. Return.

  4. Set moduleResponsesMap[requestURL] to
    fetching“.

  5. Fetch request, with processResponseConsumeBody set to the following steps
    given response response and null, failure, or a
    byte sequence bodyBytes:

    1. Set moduleResponsesMap[requestURL] to (response,
      bodyBytes).

    2. Run processCustomFetchResponse with response and
      bodyBytes.

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

This diagram illustrates how these algorithms relate to the ones above, as well as to each
other:

To fetch a worklet/module worker script graph given a url, a fetch
client settings object, a destination, a credentials mode, a
module map settings object, an onComplete algorithm, and an optional perform the fetch hook performFetch, run
these steps. onComplete must be an algorithm accepting null (on failure) or a
module script (on success).

To fetch the descendants of and link a module script module
script, given a fetch client settings object, a destination, a
visited set, an onComplete algorithm, and an optional perform the fetch hook performFetch, run
these steps. onComplete must be an algorithm accepting null (on failure) or a
module script (on success).

  1. Fetch the descendants of
    module script, given fetch client settings object, destination,
    visited set, and onFetchDescendantsComplete as defined below. If
    performFetch was given, pass it along as well.

    onFetchDescendantsComplete given result is the following algorithm:

    1. If result is null, then run onComplete given result, and
      abort these steps.

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

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

    3. If parse error is null, then:

      1. Let record be result’s record.

      2. Perform record.Link().

        This step will recursively call Link on all of
        the module’s unlinked dependencies.

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

    4. Otherwise, set result’s error
      to rethrow to parse error.

    5. Run onComplete given result.

To fetch the descendants of a module script module script, given a
fetch client settings object, a destination, a visited set, an
onComplete algorithm, and an optional perform the fetch hook performFetch, run
these steps. onComplete must be an algorithm accepting null (on failure) or a
module script (on success).

To perform the internal module script graph fetching procedure given a
moduleRequest, a fetch client settings object, a destination,
some options, a referringScript, a visited set, an
onComplete algorithm, and an optional perform the fetch hook performFetch, run
these steps. onComplete must be an algorithm accepting null (on failure) or a
module script (on success).

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, an optional moduleRequest, a boolean
isTopLevel, an onComplete algorithm,
and an optional perform the fetch hook
performFetch, run these steps. onComplete must be an algorithm accepting
null (on failure) or a module script (on success).

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

8.1.4.3

Creating scripts

To create a classic script, given a
string source, an environment settings object
settings, a URL baseURL, some script fetch options
options, and an optional boolean mutedErrors (default false):

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

To create a CSS module script, given a
string source and an environment settings object settings:

To create a JSON module script, given a
string source and an environment settings object settings:

The module type from module request steps, given a ModuleRequest
Record moduleRequest, are as follows:

  1. Let moduleType be “javascript“.

  2. If moduleRequest.[[Assertions]] has a Record entry such
    that entry.[[Key]] is “type“, then:

    1. If entry.[[Value]] is “javascript“, then set
      moduleType to null.

      This specification uses the “javascript” module type
      internally for JavaScript module scripts, so
      this step is needed to prevent modules from being imported using a “javascript” type assertion (a null moduleType will cause the
      module type allowed check to fail).

    2. Otherwise, set moduleType to entry.[[Value]].

  3. Return moduleType.

The module type allowed steps, given a string moduleType
and an environment settings object settings, are as follows:

  1. If moduleType is not “javascript“, “css“, or “json“, then return false.

  2. If moduleType is “css” and the
    CSSStyleSheet interface is not exposed in
    settings’s realm, then
    return false.

  3. Return true.

8.1.4.4

Calling scripts

To run a classic script given a classic script script
and an optional boolean rethrow errors (default false):

To run a module script given a module script script
and an optional boolean preventErrorReporting (default false):

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

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

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

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 “QuotaExceededErrorDOMException,
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.4.6

Runtime script errors

reportError

Support in all current engines.

Firefox

93+

Safari

15.4+

Chrome

95+

Opera

?

Edge

95+

Edge (Legacy)

?

Internet Explorer

No

Firefox Android

?

Safari iOS

?

Chrome Android

?

WebView Android

?

Samsung Internet

?

Opera Android

?

self.reportError(e)

Dispatches an error event at the global object for the
given value e, in the same fashion as an unhandled exception.

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
:

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

The existence of both report an error and
report an exception is confusing, and both algorithms
have known problems. You can track future cleanup in this area in issue #958.

The reportError(e) method steps are to
report the exception e.

ErrorEvent

Support in all current engines.

Firefox

27+

Safari

6+

Chrome

10+

Opera

11+

Edge

79+

Edge (Legacy)

12+

Internet Explorer

10+

Firefox Android

?

Safari iOS

?

Chrome Android

?

WebView Android

?

Samsung Internet

?

Opera Android

11+

The ErrorEvent interface is defined as follows:

[Exposed=*]
interface ErrorEvent : Event {
  constructor(DOMString type, optional ErrorEventInit eventInitDict = {});

  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;
};

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

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

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

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

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

8.1.4.7

Unhandled promise rejections

Window/rejectionhandled_event

Support in all current engines.

Firefox

69+

Safari

11+

Chrome

49+

Opera

?

Edge

79+

Edge (Legacy)

?

Internet Explorer

No

Firefox Android

?

Safari iOS

11.3+

Chrome Android

?

WebView Android

?

Samsung Internet

?

Opera Android

?

In addition to synchronous runtime script errors, scripts
may experience asynchronous promise rejections, tracked via the unhandledrejection and rejectionhandled events. Tracking these
rejections is done via the HostPromiseRejectionTracker abstract operation, but
reporting them is defined here.

To notify about rejected promises on a given environment settings object
settings object:

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.

PromiseRejectionEvent

Support in all current engines.

Firefox

69+

Safari

11+

Chrome

49+

Opera

?

Edge

79+

Edge (Legacy)

?

Internet Explorer

No

Firefox Android

?

Safari iOS

11.3+

Chrome Android

?

WebView Android

?

Samsung Internet

?

Opera Android

?

The PromiseRejectionEvent interface is
defined as follows:

[Exposed=*]
interface PromiseRejectionEvent : Event {
  constructor(DOMString type, PromiseRejectionEventInit eventInitDict);

  readonly attribute Promise<any> promise;
  readonly attribute any reason;
};

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

PromiseRejectionEvent/promise

Support in all current engines.

Firefox

69+

Safari

11+

Chrome

49+

Opera

?

Edge

79+

Edge (Legacy)

?

Internet Explorer

No

Firefox Android

?

Safari iOS

11.3+

Chrome Android

?

WebView Android

?

Samsung Internet

?

Opera Android

?

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

PromiseRejectionEvent/reason

Support in all current engines.

Firefox

69+

Safari

11+

Chrome

49+

Opera

?

Edge

79+

Edge (Legacy)

?

Internet Explorer

No

Firefox Android

?

Safari iOS

11.3+

Chrome Android

?

WebView Android

?

Samsung Internet

?

Opera Android

?

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

8.1.4.8

Import map parse results

An import map parse result is a struct that is similar to a script, and also can be stored in a script element’s
result, but is not counted as a script for other purposes. It has the following items:

An import map
An import map or null.
An error to rethrow
A JavaScript value representing an error that will prevent using this import map, when
non-null.

To create an import map parse result given a string input
and a URL baseURL:

To register an import map given a Window global and an
import map parse result result:

8.1.5

Module specifier resolution

8.1.5.1

The resolution algorithm

The resolve a module specifier algorithm is the primary entry point for
converting module specifier strings into URLs. When no import maps are involved, it is relatively straightforward, and
reduces to resolving a URL-like module specifier.

When there is a non-empty import map present, the behavior is more complex. It
checks candidate entries from all applicable module specifier
maps, from most-specific to least-specific scopes (falling back to the top-level unscoped imports), and from most-specific to least-specific
prefixes. For each candidate, the resolve
an imports match algorithm will give on the following results:

  • Successful resolution of the specifier to a URL. Then the
    resolve a module specifier algorithm will return that URL.

  • Throwing an exception. Then the resolve a module specifier algorithm will
    rethrow that exception, without any further fallbacks.

  • Failing to resolve, without an error. In this case the outer resolve a module
    specifier algorithm will move on to the next candidate.

In the end, if no successful resolution is found via any of the candidate module specifier maps, resolve a module specifier will throw
an exception. Thus the result is always either a URL or a thrown exception.

To resolve a module specifier given a script-or-null
referringScript and a string specifier:

To resolve an imports match, given a
string normalizedSpecifier, a URL-or-null asURL,
and a module specifier map specifierMap:

To resolve a URL-like module
specifier, given a string specifier and a URL
baseURL:

  1. If specifier starts with “/“, “./“, or “../“, then:

    1. Let url be the result of URL parsing
      specifier with baseURL.

    2. If url is failure, then return null.

      One way this could happen is if specifier is “../foo” and baseURL is a data: URL.

    3. Return url.

    This includes cases where specifier starts with “//“, i.e., scheme-relative URLs. Thus, url might end up with a
    different host than baseURL.

  2. Let url be the result of URL parsing
    specifier (with no base URL).

  3. If url is failure, then return null.

  4. Return url.

8.1.5.2

Import maps

An import map allows control over module specifier resolution. Import maps
are delivered via inline script elements with their type attribute set to “importmap“, and
with their child text content containing a JSON representation of the import
map.

Only one import map is processed per Document. After the first import map is
seen, others will be ignored, with their corresponding script elements generating
error events. Similarly, once any modules have been imported,
e.g., via import() expressions or script elements with their type attribute set to “module“, further
import maps will be ignored.

These restrictions, as well as the lack of support for external import maps, are
in place to keep the initial version of the feature simple. They might be lifted over time as
implementer bandwidth allows.

The simplest use of import maps is to globally remap a bare module specifier:

{
  "imports": {
    "moment": "/node_modules/moment/src/moment.js"
  }
}

This enables statements like import moment from "moment";
to work, fetching and evaluating the JavaScript module at the /node_modules/moment/src/moment.js URL.

An import map can remap a class of module specifiers into a class of URLs by using trailing
slashes, like so:

{
  "imports": {
    "moment/": "/node_modules/moment/src/"
  }
}

This enables statements like import localeData from
"moment/locale/zh-cn.js";
to work, fetching and evaluating the JavaScript module at the
/node_modules/moment/src/moment/locale/zh-cn.js URL. Such trailing-slash
mappings are often combined with bare-specifier mappings, e.g.

{
  "imports": {
    "moment": "/node_modules/moment/src/moment.js",
    "moment/": "/node_modules/moment/src/"
  }
}

so that both the “main module” specified by “moment” and the
“submodules” specified by paths such as “moment/locale/zh-cn.js” are
available.

Bare specifiers are not the only type of module specifiers which import maps can remap.
“URL-like” specifiers, i.e., those that are either parseable as absolute URLs or start with
/“, “./“, or “../“, can be
remapped as well:

{
  "imports": {
    "https://cdn.example.com/vue/dist/vue.runtime.esm.js": "/node_modules/vue/dist/vue.runtime.esm.js",
    "/js/app.mjs": "/js/app-8e0d62a03.mjs",
    "../helpers/": "https://cdn.example/helpers/"
  }
}

Note how the URL to be remapped, as well as the URL being mapped to, can be specified either
as absolute URLs, or as relative URLs starting with “/“, “./“, or “../“. (They cannot be specified as relative
URLs without those starting sigils, as those help distinguish from bare module specifiers.) Also
note how the trailing slash mapping works in
this context as well.

Such remappings operate on the post-canonicalization URL, and do not require a match between
the literal strings supplied in the import map key and the imported module specifier. So for
example, if this import map was included on https://example.com/app.html,
then not only would import "/js/app.mjs" be remapped, but so
would import "./js/app.mjs" and import "./foo/../js/app.mjs".

All previous examples have globally remapped module specifiers, by using the top-level “imports” key in the import map. The top-level “scopes
key can be used to provide localized remappings, which only apply when the referring module
matches a specific URL prefix. For example:

{
  "scopes": {
    "/a/" : {
      "moment": "/node_modules/moment/src/moment.js"
    },
    "/b/" : {
      "moment": "https://cdn.example.com/moment/src/moment.js"
    }
  }
}

With this import map, the statement import "moment" will have
different meanings depending on which referrer script contains the statement:

  • Inside scripts located under /a/, this will import /node_modules/moment/src/moment.js.

  • Inside scripts located under /b/, this will import https://cdn.example.com/moment/src/moment.js.

  • Inside scripts located under /c/, this will fail to resolve and
    thus throw an exception.

A typical usage of scopes is to allow multiple versions of the “same” module to exist in a
web application, with some parts of the module graph importing one version, and other parts
importing another version.

Scopes can overlap each other, and overlap the global “imports
specifier map. At resolution time, scopes are consulted in order of most- to least-specific,
where specificity is measured by sorting the scopes using the code unit less than
operation. So, for example, “/scope2/scope3/” is treated as more specific
than “/scope2/“, which is treated as more specific than the top-level
(unscoped) mappings.

The following import map illustrates this:

{
  "imports": {
    "a": "/a-1.mjs",
    "b": "/b-1.mjs",
    "c": "/c-1.mjs"
  },
  "scopes": {
    "/scope2/": {
      "a": "/a-2.mjs"
    },
    "/scope2/scope3/": {
      "b": "/b-3.mjs"
    }
  }
}

This results in the following resolutions (using relative URLs for brevity):

Specifier
a
b
c
Referrer
/scope1/r.mjs
/a-1.mjs
/b-1.mjs
/c-1.mjs
/scope2/r.mjs
/a-2.mjs
/b-1.mjs
/c-1.mjs
/scope2/scope3/r.mjs
/a-2.mjs
/b-3.mjs
/c-1.mjs

The child text content of a script element representing an
import map must match the following import map authoring
requirements:

  • It must be valid JSON. [JSON]

  • The JSON must represent a JSON object, with at most the two keys “imports” and “scopes“.

  • The values corresponding to the “imports” and “scopes” keys, if present, must themselves be JSON objects.

  • The value corresponding to the “imports” key, if present, must be
    a valid module specifier map.

  • The value corresponding to the “scopes” key, if present, must be a
    JSON object, whose keys are valid URL strings and whose
    values are valid module specifier
    maps.

A valid module specifier map is a JSON object that meets the following
requirements:

  • All of its keys must be nonempty.

  • All of its values must be strings.

  • Each value must be either a valid absolute URL or a
    valid URL string that starts with “/“, “./“, or “../“.

  • If a given key ends with “/“, then the corresponding
    value must also.

8.1.5.3

Import map processing model

Formally, an import map is a struct with two items:

A module specifier map is an ordered map whose keys are strings and whose values are either URLs or nulls.

An empty import map is an import map with its imports and scopes both being empty maps.

Each Window has an import map,
initially an empty import map.

Each Window has an import maps allowed boolean, initially true.

To disallow further import maps given an environment settings object
settingsObject:

  1. Let global be settingsObject’s global object.

  2. If global does not implement Window, then return.

  3. Set global’s import maps allowed to false.

Import maps are currently disallowed once any module loading has started, or once
a single import map is loaded. These restrictions might be lifted in future specification
revisions.

To parse an import map string, given a string input and a
URL baseURL:

The import map that results from this parsing algorithm is highly normalized.
For example, given a base URL of https://example.com/base/page.html, the
input

{
  "imports": {
    "/app/helper": "node_modules/helper/index.mjs",
    "lodash": "/node_modules/lodash-es/lodash.js"
  }
}

will generate an import map with imports of

«[
  "https://example.com/app/helper" → https://example.com/base/node_modules/helper/index.mjs
  "lodash" → https://example.com/node_modules/lodash-es/lodash.js
]»

and (despite nothing being present in the input string) an empty ordered map for
its scopes.

To sort and normalize a module
specifier map, given an ordered map originalMap and a
URL baseURL:

To sort and normalize scopes, given an
ordered map originalMap and a URL baseURL:

In the above two algorithms, sorting keys and scopes in descending order has the
effect of putting “foo/bar/” before “foo/“. This in
turn gives “foo/bar/” a higher priority than “foo/
during module specifier resolution.

To normalize a specifier key, given a string specifierKey and a URL baseURL:

  1. If specifierKey is the empty string, then:

    1. The user agent may report a warning to the console indicating that specifier keys may not be the empty string.

    2. Return null.

  2. Let url be the result of resolving a URL-like module specifier, given specifierKey and baseURL.

  3. If url is not null, then return the serialization of url.

  4. Return specifierKey.

8.1.6

JavaScript specification host hooks

The JavaScript specification contains a number of implementation-defined abstract
operations, that vary depending on the host environment. This section defines them for user
agent hosts.

8.1.6.1

HostEnsureCanAddPrivateElement(O)

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

  1. If O is a WindowProxy object, or implements
    Location, then return Completion { [[Type]]: throw, [[Value]]: a new
    TypeError }.

  2. Return NormalCompletion(unused).

JavaScript private fields can be applied to arbitrary objects. Since this can
dramatically complicate implementation for particularly-exotic host objects, the JavaScript
language specification provides this hook to allow hosts to reject private fields on objects
meeting a host-defined criteria. In the case of HTML, WindowProxy and
Location have complicated semantics — particularly around navigation and
security — that make implementation of private field semantics challenging, so our
implementation simply rejects those objects.

8.1.6.2

HostEnsureCanCompileStrings(realm)

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

  1. Perform ? EnsureCSPDoesNotBlockStringCompilation(realm).
    [CSP]

8.1.6.3

HostPromiseRejectionTracker(promise, operation)

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

8.1.6.4

Job-related host hooks

Reference/Global_Objects/Promise#Incumbent_settings_object_tracking

Support in one engine only.

Firefox

50+

Safari

No

Chrome

No

Opera

?

Edge

No

Edge (Legacy)

?

Internet Explorer

No

Firefox Android

?

Safari iOS

?

Chrome Android

?

WebView Android

?

Samsung Internet

?

Opera Android

?

The JavaScript specification defines Jobs to be scheduled and run later by the host, as well as
JobCallback Records which encapsulate JavaScript
functions that are called as part of jobs. The JavaScript specification contains a number of
implementation-defined abstract operations that lets the host define how jobs are
scheduled and how JobCallbacks are handled. HTML uses these abstract operations to track the incumbent settings
object in promises and FinalizationRegistry callbacks by saving and
restoring the incumbent settings object and a JavaScript execution
context for the active script in JobCallbacks. This section defines them for
user agent hosts.

8.1.6.4.1

HostCallJobCallback(callback, V,
argumentsList)

JavaScript contains an implementation-defined HostCallJobCallback(callback, V,
argumentsList) abstract operation to let hosts restore state when invoking JavaScript
callbacks from inside tasks. User agents must use the following implementation: [JAVASCRIPT]

8.1.6.4.2

HostEnqueueFinalizationRegistryCleanupJob(finalizationRegistry)

JavaScript has the ability to register objects with FinalizationRegistry objects,
in order to schedule a cleanup action if they are found to be garbage collected. The JavaScript
specification contains an implementation-defined HostEnqueueFinalizationRegistryCleanupJob(finalizationRegistry)
abstract operation to schedule the cleanup action.

The timing and occurrence of cleanup work is implementation-defined
in the JavaScript specification. User agents might differ in when and whether an object is garbage
collected, affecting both whether the return value of the WeakRef.prototype.deref()
method is undefined, and whether FinalizationRegistry cleanup callbacks occur. There
are well-known cases in popular web browsers where objects are not accessible to JavaScript, but
they remain retained by the garbage collector indefinitely. HTML clears kept-alive
WeakRef objects in the perform a microtask checkpoint algorithm. Authors
would be best off not depending on the timing details of garbage collection implementations.

Cleanup actions do not take place interspersed with synchronous JavaScript execution, but
rather happen in queued tasks. User agents must use the
following implementation: [JAVASCRIPT]

8.1.6.4.3

HostEnqueuePromiseJob(job,
realm)

JavaScript contains an implementation-defined HostEnqueuePromiseJob(job, realm)
abstract operation to schedule Promise-related operations. HTML schedules these operations in the
microtask queue. User agents must use the following implementation: [JAVASCRIPT]

8.1.6.4.4

HostMakeJobCallback(callable)

JavaScript contains an implementation-defined HostMakeJobCallback(callable) abstract operation
to let hosts attach state to JavaScript callbacks that are called from inside tasks. User agents must use the following implementation: [JAVASCRIPT]

8.1.6.5

Module-related host hooks

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 keyed by tuples consisting of a URL record and a string.
The URL record is the request URL at which
the module was fetched, and the string indicates the type of the module (e.g. “javascript“). The module map’s values are either a module
script, null (used to represent failed fetches), or a placeholder value “fetching“. Module maps are used to ensure
that imported module scripts are only fetched, parsed, and evaluated once per
Document or worker.

Since module maps are keyed by (URL, module type), the
following code will create three separate entries in the module map, since it
results in three different (URL, module type) tuples (all with “javascript” type):

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.

Since module type is also part of the module map key, the following code will
create two separate entries in the module map (the type is “javascript” for the first, and “css” for the second):

<script type=module>
  import "https://example.com/module";
</script>
<script type=module>
  import "https://example.com/module" assert { type: "css" };
</script>

This can result in two separate fetches and two separate module evaluations being performed.
This is a willful violation of a constraint recommended (but not required) by the
import assertions specification stating that each call to HostResolveImportedModule
with the same (referencingScriptOrModule, moduleRequest.[[Specifier]]) pair
must return the same Module Record. [JSIMPORTASSERTIONS]

In practice, due to the as-yet-unspecified memory cache (see issue #6110) the resource may only be fetched
once in WebKit and Blink-based browsers. Additionally, as long as all module types are mutually
exclusive, the module type check in fetch a single module script will fail for at
least one of the imports, so at most one module evaluation will occur.

The purpose of including the type in the module map key is so that an import
with the wrong type assertion does not prevent a different import of the same specifier but with
the correct type from succeeding.

JavaScript module scripts are the default import type when importing from another JavaScript
module; that is, when an import statement lacks a type import assertion the imported module script’s type will be JavaScript.
Attempting to import a JavaScript resource using an import statement with
a type import assertion will fail:

<script type="module">
    // All of the following will fail, assuming that the imported .mjs files are served with a
    // JavaScript MIME type. JavaScript module scripts are the default and cannot be imported with
    // any import type assertion.
    import foo from "./foo.mjs" assert { type: "javascript" };
    import foo2 from "./foo2.mjs" assert { type: "js" };
    import foo3 from "./foo3.mjs" assert { type: "" };
    await import("./foo4.mjs", { assert: { type: null } });
    await import("./foo5.mjs", { assert: { type: undefined } });
</script>

8.1.6.5.1

HostGetImportMetaProperties(moduleRecord)

Reference/Operators/import.meta

Support in all current engines.

Firefox

62+

Safari

11.1+

Chrome

64+

Opera

?

Edge

79+

Edge (Legacy)

?

Internet Explorer

No

Firefox Android

?

Safari iOS

12+

Chrome Android

?

WebView Android

?

Samsung Internet

?

Opera Android

?

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

8.1.6.5.2

HostImportModuleDynamically(referencingScriptOrModule,
moduleRequest, promiseCapability)

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

8.1.6.5.3

HostResolveImportedModule(referencingScriptOrModule,
moduleRequest)

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

8.1.6.5.4

HostGetSupportedImportAssertions()

The Import Assertions proposal contains an implementation-defined
HostGetSupportedImportAssertions
abstract operation. User agents must use the following implementation: [JSIMPORTASSERTIONS]

  1. Return « “type” ».

8.1.7

Event loops

8.1.7.1

Definitions

To coordinate events, user interaction, scripts, rendering, networking, and so forth, user
agents must use event loops as
described in this section. Each agent has an associated event loop, which is unique to that agent.

The event loop of a similar-origin window
agent is known as a window event loop. The event loop of a dedicated worker agent,
shared worker agent, or service worker agent is known as a worker
event loop. And the event loop of a
worklet agent is known as a worklet event loop.

Event loops do not necessarily correspond to implementation
threads. For example, multiple window event loops could
be cooperatively scheduled in a single thread.

However, for the various worker agents that are allocated with
[[CanBlock]] set to true, the JavaScript specification does place requirements on them regarding
forward progress, which effectively amount to requiring dedicated per-agent threads
in those cases.

An event loop has one or more task queues. A
task queue is a set of tasks.

Task queues are sets,
not queues, because the event
loop processing model grabs the first runnable task
from the chosen queue, instead of dequeuing the first task.

The microtask queue is not a task queue.

Tasks encapsulate algorithms that are responsible for such work as:

Events

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

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

Parsing

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

Callbacks

Calling a callback is often done by a dedicated task.

Using a resource

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

Reacting to DOM manipulation

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

Formally, a task is a
struct which has:

Steps
A series of steps specifying the work to be done by the task.
A source
One of the task sources, used to group and serialize
related tasks.
A document
A Document associated with the task, or null for tasks that are not in a
window event loop.
A script evaluation environment settings object set
A set of environment settings
objects used for tracking script evaluation during the task.

A task is runnable
if its document is either null or fully
active.

Per its source field, each task is defined as coming from a specific task
source. For each event loop, every task source must be associated
with a specific task queue.

Essentially, task sources are used within
standards to separate logically-different types of tasks, which a user agent might wish to
distinguish between. Task queues are used by user agents to
coalesce task sources within a given event loop.

For example, a user agent could have one task queue for mouse and
key events (to which the user interaction task source is associated), and another to
which all other task sources are associated. Then, using the
freedom granted in the initial step of the event loop
processing model, it could give keyboard and mouse events preference over other tasks
three-quarters of the time, keeping the interface responsive but not starving other task queues.
Note that in this setup, the processing model still enforces that the user agent would never
process events from any one task source out of order.

Each event loop has a currently running task, which is either a task or null. Initially, this is null. It is used to handle
reentrancy.

Each event loop has a microtask queue, which is a queue of
microtasks, initially empty. A microtask is a
colloquial way of referring to a task that was created via the
queue a microtask algorithm.

Each event loop has a performing a microtask checkpoint boolean,
which is initially false. It is used to prevent reentrant invocation of the perform a
microtask checkpoint algorithm.

Each window event loop has a
last render opportunity time, initially set to zero.

Each window event loop has a
last idle period start time, initially set to zero.

To get the same-loop windows for a window event loop loop,
return all Window objects whose relevant agent’s
event loop is loop.

8.1.7.2

Queuing tasks

To queue a task on a task source source, which
performs a series of steps steps, optionally given an event loop event loop
and a document document:

Failing to pass an event loop and document to queue a task means
relying on the ambiguous and poorly-specified implied event loop and implied
document concepts. Specification authors should either always pass these values, or use the
wrapper algorithms queue a global task or queue an element task
instead. Using the wrapper algorithms is recommended.

To queue a global task on a task source source, with
a global object global and a series of steps steps:

  1. Let event loop be global’s relevant agent’s event loop.

  2. Let document be global’s associated Document, if global is
    a Window object; otherwise null.

  3. Queue a task given source, event loop,
    document, and steps.

To queue an element task on a task source source,
with an element element and a series of steps steps:

  1. Let global be element’s relevant global
    object.

  2. Queue a global task given source, global, and
    steps.

To queue a microtask which performs a series of steps steps,
optionally given an event loop event loop and a document document:

It is possible for a microtask to be moved to a regular task
queue, if, during its initial execution, it spins the
event loop. This is the only case in which the source, document,
and script evaluation environment settings object set of the microtask are consulted;
they are ignored by the perform a microtask checkpoint algorithm.

The implied event loop when queuing a task is the one that can deduced from the
context of the calling algorithm. This is generally unambiguous, as most specification algorithms
only ever involve a single agent (and thus a single event loop). The
exception is algorithms involving or specifying cross-agent communication (e.g., between a window
and a worker); for those cases, the implied event loop concept must not be relied
upon and specifications must explicitly provide an event loop when queuing a task or microtask.

The implied document when queuing a task on an event loop event
loop is determined as follows:

Both implied event loop and implied
document are vaguely-defined and have a lot of action-at-a-distance. The hope is to remove
these, especially implied document. See issue #4980.

8.1.7.3

Processing model

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

When a user agent is to perform a microtask checkpoint:

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

Algorithm steps that say to spin the event loop until a condition goal is
met are equivalent to substituting in the following algorithm steps:

Unlike other algorithms in this and other specifications, which behave similar to
programming-language function calls, spin the event loop is more like a macro, which
saves typing and indentation at the usage site by expanding into a series of steps and
operations.

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

Generic task sources

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

8.1.7.5

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

  • performing heavy computation;

  • displaying a user-facing prompt;

  • performing operations which could require involving outside systems (i.e. “going out of
    process”).

The next complication is that, in algorithm sections that are in parallel, you
must not create or manipulate objects associated to a specific 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
Infra, 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 global
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 queuing a global
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. Finally, you must indicate which global
object your queued task is associated with; this ensures that if that global object is
inactive, the task does not run.

The base primitive, on which queue a global task builds, is the
queue a task algorithm. In general, queue a global task is better
because it automatically picks the right event loop and, where appropriate, document. Older specifications often use queue a
task combined with the implied event loop and implied document
concepts, but this is discouraged.

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 global task, on a specified task source and given an
    appropriate global object, to convert the realm-agnostic result back into observable
    effects on the observable world of JavaScript objects on the event loop.

8.1.8

Events

8.1.8.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 is a struct with two items:

Event handlers are exposed in 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.

For both of these two ways, the event handler is exposed
through a name, which is a string that always starts with
on” and is followed by the name of the event for which the handler is
intended.

Most of the time, the object that exposes an event handler
is the same as the object on which the corresponding event listener is added.
However, the body and frameset elements expose several event
handlers that act upon the element’s Window object, if one exists. In either
case, we call the object an event handler acts upon the target of that event
handler.

To determine the target of an event
handler, given an EventTarget object eventTarget on which the event handler is exposed, and an event handler name
name, the following steps are taken:

Each EventTarget object that has one or more event handlers specified
has an associated event handler map, which is a map
of strings representing names of event
handlers to event handlers.

When an EventTarget object that has one or more event handlers
specified is created, its event handler map must be initialized such that it contains
an entry for each event
handler that has that object as target, with
items in those event handlers set to their initial
values.

The order of the entries of event handler
map could be arbitrary. It is not observable through any algorithms that operate on the
map.

Entries are not created in the event handler
map of an object for event handlers that are merely exposed on that object,
but have some other object as their targets.

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.

The getter of an event handler IDL attribute
with name name, when called, must run these steps:

  1. Let eventTarget be the result of determining the target of an event
    handler given this object and name.

  2. If eventTarget is null, then return null.

  3. Return the result of getting the current value of the event handler given
    eventTarget and name.

The setter of an event handler IDL attribute
with name name, when called, must run these steps:

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.

The following attribute change
steps are used to synchronize between event handler content attributes and
event handlers: [DOM]

Per the DOM Standard, these steps are run even if oldValue and
value are identical (setting an attribute to its current value), but not if
oldValue and value are both null (removing an attribute that doesn’t
currently exist). [DOM]

To deactivate an event handler given an EventTarget object
eventTarget and a string name that is the name of an event handler, run these steps:

  1. Let handlerMap be eventTarget’s event handler
    map.

  2. Let eventHandler be handlerMap[name].

  3. Set eventHandler’s value to
    null.

  4. Let listener be eventHandler’s listener.

  5. If listener is not null, then remove an event listener with
    eventTarget and listener.

  6. Set eventHandler’s listener to
    null.

To erase all event listeners and handlers given an EventTarget object
eventTarget, run these steps:

This algorithm is used to define document.open().

To activate an event handler given an EventTarget object
eventTarget and a string name that is the name of an event handler, run these steps:

The event listener registration happens only if the event
handler’s value is being set to non-null, and
the event handler is not already activated. Since listeners
are called in the order they were registered, assuming no deactivation occurred, the order of event listeners for a particular event type
will always be:

  1. the event listeners registered with addEventListener() before the first time the
    event handler’s value was set to non-null

  2. then the callback to which it is currently set, if any

  3. and finally the event listeners registered with addEventListener() after the first
    time the event handler’s value was set to non-null.

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>

However, in the following example, the event handler is deactivated after its initial activation (and its event listener is removed),
before being reactivated at a later time. The page will show five alerts with “ONE”, “TWO”,
“THREE”, “FOUR”, and “FIVE” respectively, in order.

<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 is activated here
 button.addEventListener('click', function () { alert('TWO') }, false);
 button.onclick = null;                                 // but deactivated here
 button.addEventListener('click', function () { alert('THREE') }, false);
 button.onclick = function () { alert('FOUR'); };       // and re-activated here
 button.addEventListener('click', function () { alert('FIVE') }, 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 EventTarget object
eventTarget, a string name representing the name of an event handler, and an
Event object event is as follows:

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

[LegacyTreatNonObjectAsNull]
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:

  • The onerror handlers on global objects, where
    returning true cancels the event.

  • The onbeforeunload handler, where
    returning any non-null and non-undefined value will cancel the event.

For historical reasons, the onerror handler has different
arguments:

[LegacyTreatNonObjectAsNull]
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:

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

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

  • An uncompiled script body
  • A location where the script body originated, in case an error needs to be reported

When the user agent is to get the
current value of the event handler given an EventTarget object
eventTarget and a string name that is the name of an event handler, it must run these
steps:

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

HTMLMediaElement/abort_event

Support in all current engines.

Firefox

9+

Safari

3.1+

Chrome

1+

Opera

12.1+

Edge

79+

Edge (Legacy)

12+

Internet Explorer

9+

Firefox Android

?

Safari iOS

3+

Chrome Android

?

WebView Android

?

Samsung Internet

?

Opera Android

12.1+

abort
onauxclick

Element/auxclick_event

Firefox

53+

Safari

No

Chrome

55+

Opera

?

Edge

79+

Edge (Legacy)

?

Internet Explorer

No

Firefox Android

53+

Safari iOS

?

Chrome Android

?

WebView Android

?

Samsung Internet

?

Opera Android

?

auxclick
onbeforeinput beforeinput
onbeforematch beforematch
oncancel

HTMLDialogElement/cancel_event

Support in all current engines.

Firefox

98+

Safari

15.4+

Chrome

37+

Opera

?

Edge

79+

Edge (Legacy)

?

Internet Explorer

No

Firefox Android

?

Safari iOS

?

Chrome Android

No

WebView Android

?

Samsung Internet

?

Opera Android

?

cancel
oncanplay

HTMLMediaElement/canplay_event

Support in all current engines.

Firefox

3.5+

Safari

3.1+

Chrome

3+

Opera

10.5+

Edge

79+

Edge (Legacy)

12+

Internet Explorer

9+

Firefox Android

?

Safari iOS

3+

Chrome Android

?

WebView Android

37+

Samsung Internet

?

Opera Android

11+

canplay
oncanplaythrough

HTMLMediaElement/canplaythrough_event

Support in all current engines.

Firefox

3.5+

Safari

3.1+

Chrome

3+

Opera

10.5+

Edge

79+

Edge (Legacy)

12+

Internet Explorer

9+

Firefox Android

?

Safari iOS

3+

Chrome Android

?

WebView Android

37+

Samsung Internet

?

Opera Android

11+

canplaythrough
onchange

HTMLElement/change_event

Support in all current engines.

Firefox

1+

Safari

3+

Chrome

1+

Opera

9+

Edge

79+

Edge (Legacy)

12+

Internet Explorer

9+

Firefox Android

?

Safari iOS

?

Chrome Android

?

WebView Android

?

Samsung Internet

?

Opera Android

10.1+

change
onclick

Element/click_event

Support in all current engines.

Firefox

6+

Safari

3+

Chrome

1+

Opera

11.6+

Edge

79+

Edge (Legacy)

12+

Internet Explorer

9+

Firefox Android

6+

Safari iOS

1+

Chrome Android

?

WebView Android

?

Samsung Internet

?

Opera Android

12.1+

click
onclose close
oncontextlost contextlost
oncontextmenu contextmenu
oncontextrestored contextrestored
oncuechange

HTMLTrackElement/cuechange_event

Support in all current engines.

Firefox

68+

Safari

10+

Chrome

32+

Opera

19+

Edge

79+

Edge (Legacy)

14+

Internet Explorer

No

Firefox Android

?

Safari iOS

?

Chrome Android

?

WebView Android

4.4.3+

Samsung Internet

?

Opera Android

19+

cuechange
ondblclick

Element/dblclick_event

Support in all current engines.

Firefox

6+

Safari

3+

Chrome

1+

Opera

11.6+

Edge

79+

Edge (Legacy)

12+

Internet Explorer

8+

Firefox Android

6+

Safari iOS

1+

Chrome Android

No

WebView Android

?

Samsung Internet

?

Opera Android

12.1+

dblclick
ondrag drag
ondragend dragend
ondragenter dragenter
ondragleave dragleave
ondragover dragover
ondragstart dragstart
ondrop drop
ondurationchange

HTMLMediaElement/durationchange_event

Support in all current engines.

Firefox

3.5+

Safari

3.1+

Chrome

3+

Opera

10.5+

Edge

79+

Edge (Legacy)

12+

Internet Explorer

9+

Firefox Android

?

Safari iOS

3+

Chrome Android

?

WebView Android

37+

Samsung Internet

?

Opera Android

11+

durationchange
onemptied

HTMLMediaElement/emptied_event

Support in all current engines.

Firefox

3.5+

Safari

3.1+

Chrome

3+

Opera

10.5+

Edge

79+

Edge (Legacy)

12+

Internet Explorer

9+

Firefox Android

?

Safari iOS

3+

Chrome Android

?

WebView Android

37+

Samsung Internet

?

Opera Android

11+

emptied
onended

HTMLMediaElement/ended_event

Support in all current engines.

Firefox

3.5+

Safari

3.1+

Chrome

3+

Opera

10.5+

Edge

79+

Edge (Legacy)

12+

Internet Explorer

9+

Firefox Android

?

Safari iOS

3+

Chrome Android

?

WebView Android

37+

Samsung Internet

?

Opera Android

11+

ended
onformdata formdata
oninput

HTMLElement/input_event

Support in all current engines.

Firefox

6+

Safari

3.1+

Chrome

1+

Opera

11.6+

Edge

79+

Edge (Legacy)

No

Internet Explorer

🔰 9+

Firefox Android

?

Safari iOS

?

Chrome Android

?

WebView Android

?

Samsung Internet

?

Opera Android

12+

input
oninvalid invalid
onkeydown

Element/keydown_event

Support in all current engines.

Firefox

6+

Safari

1.2+

Chrome

1+

Opera

12.1+

Edge

79+

Edge (Legacy)

12+

Internet Explorer

9+

Firefox Android

?

Safari iOS

?

Chrome Android

?

WebView Android

?

Samsung Internet

?

Opera Android

12.1+

keydown
onkeypress keypress
onkeyup

Element/keyup_event

Support in all current engines.

Firefox

6+

Safari

1.2+

Chrome

1+

Opera

12.1+

Edge

79+

Edge (Legacy)

12+

Internet Explorer

9+

Firefox Android

?

Safari iOS

?

Chrome Android

?

WebView Android

?

Samsung Internet

?

Opera Android

12.1+

keyup
onloadeddata

HTMLMediaElement/loadeddata_event

Support in all current engines.

Firefox

3.5+

Safari

3.1+

Chrome

3+

Opera

10.5+

Edge

79+

Edge (Legacy)

12+

Internet Explorer

9+

Firefox Android

?

Safari iOS

3+

Chrome Android

?

WebView Android

37+

Samsung Internet

?

Opera Android

11+

loadeddata
onloadedmetadata

HTMLMediaElement/loadedmetadata_event

Support in all current engines.

Firefox

3.5+

Safari

3.1+

Chrome

3+

Opera

10.5+

Edge

79+

Edge (Legacy)

12+

Internet Explorer

9+

Firefox Android

?

Safari iOS

3+

Chrome Android

?

WebView Android

37+

Samsung Internet

?

Opera Android

11+

loadedmetadata
onloadstart

HTMLMediaElement/loadstart_event

Support in all current engines.

Firefox

6+

Safari

4+

Chrome

1+

Opera

12.1+

Edge

79+

Edge (Legacy)

12+

Internet Explorer

9+

Firefox Android

?

Safari iOS

3+

Chrome Android

?

WebView Android

?

Samsung Internet

?

Opera Android

12.1+

loadstart
onmousedown

Element/mousedown_event

Support in all current engines.

Firefox

6+

Safari

4+

Chrome

2+

Opera

11.6+

Edge

79+

Edge (Legacy)

12+

Internet Explorer

9+

Firefox Android

?

Safari iOS

?

Chrome Android

?

WebView Android

37+

Samsung Internet

?

Opera Android

12.1+

mousedown
onmouseenter

Element/mouseenter_event

Support in all current engines.

Firefox

10+

Safari

7+

Chrome

30+

Opera

?

Edge

79+

Edge (Legacy)

12+

Internet Explorer

5.5+

Firefox Android

?

Safari iOS

?

Chrome Android

?

WebView Android

37+

Samsung Internet

?

Opera Android

?

mouseenter
onmouseleave

Element/mouseleave_event

Support in all current engines.

Firefox

10+

Safari

7+

Chrome

30+

Opera

?

Edge

79+

Edge (Legacy)

12+

Internet Explorer

5.5+

Firefox Android

?

Safari iOS

?

Chrome Android

?

WebView Android

37+

Samsung Internet

?

Opera Android

?

mouseleave
onmousemove

Element/mousemove_event

Support in all current engines.

Firefox

6+

Safari

4+

Chrome

2+

Opera

11.6+

Edge

79+

Edge (Legacy)

12+

Internet Explorer

9+

Firefox Android

?

Safari iOS

?

Chrome Android

?

WebView Android

37+

Samsung Internet

?

Opera Android

12.1+

mousemove
onmouseout

Element/mouseout_event

Support in all current engines.

Firefox

6+

Safari

1+

Chrome

1+

Opera

12.1+

Edge

79+

Edge (Legacy)

12+

Internet Explorer

9+

Firefox Android

?

Safari iOS

?

Chrome Android

?

WebView Android

37+

Samsung Internet

?

Opera Android

12.1+

mouseout
onmouseover

Element/mouseover_event

Support in all current engines.

Firefox

6+

Safari

4+

Chrome

2+

Opera

9.5+

Edge

79+

Edge (Legacy)

12+

Internet Explorer

9+

Firefox Android

?

Safari iOS

?

Chrome Android

?

WebView Android

37+

Samsung Internet

?

Opera Android

10.1+

mouseover
onmouseup

Element/mouseup_event

Support in all current engines.

Firefox

6+

Safari

4+

Chrome

2+

Opera

11.6+

Edge

79+

Edge (Legacy)

12+

Internet Explorer

9+

Firefox Android

?

Safari iOS

?

Chrome Android

?

WebView Android

37+

Samsung Internet

?

Opera Android

12.1+

mouseup
onpause

HTMLMediaElement/pause_event

Support in all current engines.

Firefox

3.5+

Safari

3.1+

Chrome

3+

Opera

10.5+

Edge

79+

Edge (Legacy)

12+

Internet Explorer

9+

Firefox Android

?

Safari iOS

3+

Chrome Android

?

WebView Android

37+

Samsung Internet

?

Opera Android

11+

pause
onplay

HTMLMediaElement/play_event

Support in all current engines.

Firefox

3.5+

Safari

3.1+

Chrome

3+

Opera

10.5+

Edge

79+

Edge (Legacy)

12+

Internet Explorer

9+

Firefox Android

?

Safari iOS

3+

Chrome Android

?

WebView Android

37+

Samsung Internet

?

Opera Android

11+

play
onplaying

HTMLMediaElement/playing_event

Support in all current engines.

Firefox

3.5+

Safari

3.1+

Chrome

3+

Opera

10.5+

Edge

79+

Edge (Legacy)

12+

Internet Explorer

9+

Firefox Android

?

Safari iOS

3+

Chrome Android

?

WebView Android

37+

Samsung Internet

?

Opera Android

11+

playing
onprogress

HTMLMediaElement/progress_event

Support in all current engines.

Firefox

6+

Safari

3.1+

Chrome

1+

Opera

12.1+

Edge

79+

Edge (Legacy)

12+

Internet Explorer

9+

Firefox Android

?

Safari iOS

3+

Chrome Android

?

WebView Android

?

Samsung Internet

?

Opera Android

12.1+

progress
onratechange

HTMLMediaElement/ratechange_event

Support in all current engines.

Firefox

3.5+

Safari

3.1+

Chrome

3+

Opera

10.5+

Edge

79+

Edge (Legacy)

12+

Internet Explorer

9+

Firefox Android

?

Safari iOS

3+

Chrome Android

?

WebView Android

37+

Samsung Internet

?

Opera Android

11+

ratechange
onreset reset
onsecuritypolicyviolation securitypolicyviolation
onseeked

HTMLMediaElement/seeked_event

Support in all current engines.

Firefox

3.5+

Safari

3.1+

Chrome

3+

Opera

10.5+

Edge

79+

Edge (Legacy)

12+

Internet Explorer

9+

Firefox Android

?

Safari iOS

3+

Chrome Android

?

WebView Android

37+

Samsung Internet

?

Opera Android

11+

seeked
onseeking

HTMLMediaElement/seeking_event

Support in all current engines.

Firefox

3.5+

Safari

3.1+

Chrome

3+

Opera

10.5+

Edge

79+

Edge (Legacy)

12+

Internet Explorer

9+

Firefox Android

?

Safari iOS

3+

Chrome Android

?

WebView Android

37+

Samsung Internet

?

Opera Android

11+

seeking
onselect

HTMLInputElement/select_event

Support in all current engines.

Firefox

6+

Safari

1+

Chrome

1+

Opera

12.1+

Edge

79+

Edge (Legacy)

12+

Internet Explorer

9+

Firefox Android

?

Safari iOS

?

Chrome Android

?

WebView Android

?

Samsung Internet

?

Opera Android

12.1+

HTMLTextAreaElement/select_event

Support in all current engines.

Firefox

6+

Safari

1+

Chrome

1+

Opera

12.1+

Edge

79+

Edge (Legacy)

12+

Internet Explorer

9+

Firefox Android

?

Safari iOS

?

Chrome Android

?

WebView Android

?

Samsung Internet

?

Opera Android

12.1+

select
onslotchange

HTMLSlotElement/slotchange_event

Support in all current engines.

Firefox

63+

Safari

10.1+

Chrome

53+

Opera

?

Edge

79+

Edge (Legacy)

?

Internet Explorer

No

Firefox Android

?

Safari iOS

?

Chrome Android

?

WebView Android

?

Samsung Internet

?

Opera Android

?

slotchange
onstalled

HTMLMediaElement/stalled_event

Support in all current engines.

Firefox

3.5+

Safari

3.1+

Chrome

3+

Opera

10.5+

Edge

79+

Edge (Legacy)

12+

Internet Explorer

9+

Firefox Android

?

Safari iOS

3+

Chrome Android

?

WebView Android

37+

Samsung Internet

?

Opera Android

11+

stalled
onsubmit

HTMLFormElement/submit_event

Support in all current engines.

Firefox

1+

Safari

3+

Chrome

1+

Opera

8+

Edge

79+

Edge (Legacy)

12+

Internet Explorer

9+

Firefox Android

?

Safari iOS

1+

Chrome Android

?

WebView Android

?

Samsung Internet

?

Opera Android

10.1+

submit
onsuspend

HTMLMediaElement/suspend_event

Support in all current engines.

Firefox

3.5+

Safari

3.1+

Chrome

3+

Opera

10.5+

Edge

79+

Edge (Legacy)

12+

Internet Explorer

9+

Firefox Android

?

Safari iOS

3+

Chrome Android

?

WebView Android

37+

Samsung Internet

?

Opera Android

11+

suspend

HTMLMediaElement/timeupdate_event

Support in all current engines.

Firefox

3.5+

Safari

3.1+

Chrome

3+

Opera

10.5+

Edge

79+

Edge (Legacy)

12+

Internet Explorer

9+

Firefox Android

?

Safari iOS

3+

Chrome Android

?

WebView Android

37+

Samsung Internet

?

Opera Android

11+

ontoggle toggle
onvolumechange

HTMLMediaElement/volumechange_event

Support in all current engines.

Firefox

6+

Safari

3.1+

Chrome

1+

Opera

12.1+

Edge

79+

Edge (Legacy)

12+

Internet Explorer

9+

Firefox Android

?

Safari iOS

3+

Chrome Android

?

WebView Android

37+

Samsung Internet

?

Opera Android

12.1+

volumechange
onwaiting

HTMLMediaElement/waiting_event

Support in all current engines.

Firefox

6+

Safari

3.1+

Chrome

1+

Opera

12.1+

Edge

79+

Edge (Legacy)

12+

Internet Explorer

9+

Firefox Android

?

Safari iOS

3+

Chrome Android

?

WebView Android

37+

Samsung Internet

?

Opera Android

12.1+

waiting
onwebkitanimationend webkitAnimationEnd
onwebkitanimationiteration webkitAnimationIteration
onwebkitanimationstart webkitAnimationStart
onwebkittransitionend webkitTransitionEnd
onwheel

Element/wheel_event

Support in all current engines.

Firefox

17+

Safari

7+

Chrome

31+

Opera

?

Edge

79+

Edge (Legacy)

12+

Internet Explorer

9+

Firefox Android

?

Safari iOS

No

Chrome Android

?

WebView Android

?

Samsung Internet

?

Opera Android

?

wheel

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

Element/blur_event

Support in all current engines.

Firefox

24+

Safari

3.1+

Chrome

1+

Opera

11.6+

Edge

79+

Edge (Legacy)

12+

Internet Explorer

9+

Firefox Android

?

Safari iOS

?

Chrome Android

?

WebView Android

?

Samsung Internet

?

Opera Android

12.1+

Window/blur_event

Support in all current engines.

Firefox

6+

Safari

5.1+

Chrome

5+

Opera

12.1+

Edge

79+

Edge (Legacy)

12+

Internet Explorer

11

Firefox Android

?

Safari iOS

?

Chrome Android

?

WebView Android

37+

Samsung Internet

?

Opera Android

12.1+

blur
onerror

Window/error_event

Support in all current engines.

Firefox

6+

Safari

5.1+

Chrome

10+

Opera

?

Edge

79+

Edge (Legacy)

12+

Internet Explorer

9+

Firefox Android

?

Safari iOS

?

Chrome Android

?

WebView Android

37+

Samsung Internet

?

Opera Android

?

error
onfocus

Element/focus_event

Support in all current engines.

Firefox

24+

Safari

3.1+

Chrome

1+

Opera

11.6+

Edge

79+

Edge (Legacy)

12+

Internet Explorer

9+

Firefox Android

?

Safari iOS

?

Chrome Android

?

WebView Android

?

Samsung Internet

?

Opera Android

12.1+

Window/focus_event

Support in all current engines.

Firefox

6+

Safari

5.1+

Chrome

5+

Opera

12.1+

Edge

79+

Edge (Legacy)

12+

Internet Explorer

11

Firefox Android

?

Safari iOS

?

Chrome Android

?

WebView Android

37+

Samsung Internet

?

Opera Android

12.1+

focus
onload load
onresize resize
onscroll

Document/scroll_event

Support in all current engines.

Firefox

6+

Safari

2+

Chrome

1+

Opera

11.6+

Edge

79+

Edge (Legacy)

12+

Internet Explorer

9+

Firefox Android

?

Safari iOS

?

Chrome Android

?

WebView Android

?

Samsung Internet

?

Opera Android

12+

Element/scroll_event

Support in all current engines.

Firefox

6+

Safari

1.3+

Chrome

1+

Opera

12.1+

Edge

79+

Edge (Legacy)

12+

Internet Explorer

9+

Firefox Android

?

Safari iOS

?

Chrome Android

?

WebView Android

?

Samsung Internet

?

Opera Android

12.1+

scroll
onscrollend scrollend

We call the set of the names of the
event handlers listed in the first column of this table the
Window-reflecting body element event handler set.

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

Window/afterprint_event

Support in all current engines.

Firefox

6+

Safari

13+

Chrome

63+

Opera

?

Edge

79+

Edge (Legacy)

12+

Internet Explorer

9+

Firefox Android

?

Safari iOS

?

Chrome Android

?

WebView Android

?

Samsung Internet

?

Opera Android

?

afterprint
onbeforeprint

Window/beforeprint_event

Support in all current engines.

Firefox

6+

Safari

13+

Chrome

63+

Opera

?

Edge

79+

Edge (Legacy)

12+

Internet Explorer

9+

Firefox Android

?

Safari iOS

?

Chrome Android

?

WebView Android

?

Samsung Internet

?

Opera Android

?

beforeprint
onbeforeunload

Window/beforeunload_event

Support in all current engines.

Firefox

1+

Safari

3+

Chrome

1+

Opera

12+

Edge

79+

Edge (Legacy)

12+

Internet Explorer

4+

Firefox Android

?

Safari iOS

1+

Chrome Android

?

WebView Android

?

Samsung Internet

?

Opera Android

12+

beforeunload
onhashchange

Window/hashchange_event

Support in all current engines.

Firefox

3.6+

Safari

5+

Chrome

8+

Opera

10.6+

Edge

79+

Edge (Legacy)

12+

Internet Explorer

8+

Firefox Android

?

Safari iOS

5+

Chrome Android

?

WebView Android

37+

Samsung Internet

?

Opera Android

11+

hashchange
onlanguagechange

Window/languagechange_event

Support in all current engines.

Firefox

32+

Safari

10.1+

Chrome

37+

Opera

?

Edge

79+

Edge (Legacy)

?

Internet Explorer

No

Firefox Android

4+

Safari iOS

?

Chrome Android

?

WebView Android

?

Samsung Internet

4.0+

Opera Android

?

languagechange
onmessage

Window/message_event

Support in all current engines.

Firefox

9+

Safari

4+

Chrome

60+

Opera

?

Edge

79+

Edge (Legacy)

12+

Internet Explorer

8+

Firefox Android

?

Safari iOS

4+

Chrome Android

?

WebView Android

?

Samsung Internet

?

Opera Android

47+

message
onmessageerror

HTMLMediaElement/error_event

Support in all current engines.

Firefox

6+

Safari

3.1+

Chrome

1+

Opera

11.6+

Edge

79+

Edge (Legacy)

12+

Internet Explorer

9+

Firefox Android

?

Safari iOS

3+

Chrome Android

?

WebView Android

?

Samsung Internet

?

Opera Android

12+

Window/messageerror_event

Firefox

57+

Safari

No

Chrome

60+

Opera

?

Edge

79+

Edge (Legacy)

18

Internet Explorer

No

Firefox Android

?

Safari iOS

?

Chrome Android

?

WebView Android

?

Samsung Internet

?

Opera Android

47+

messageerror
onoffline

Window/offline_event

Support in all current engines.

Firefox

9+

Safari

4+

Chrome

3+

Opera

?

Edge

79+

Edge (Legacy)

12+

Internet Explorer

9+

Firefox Android

?

Safari iOS

3+

Chrome Android

?

WebView Android

37+

Samsung Internet

?

Opera Android

?

offline
ononline

Window/online_event

Support in all current engines.

Firefox

9+

Safari

4+

Chrome

3+

Opera

?

Edge

79+

Edge (Legacy)

12+

Internet Explorer

9+

Firefox Android

?

Safari iOS

3+

Chrome Android

?

WebView Android

37+

Samsung Internet

?

Opera Android

?

online
onpagehide pagehide
onpageshow pageshow
onpopstate

Window/popstate_event

Support in all current engines.

Firefox

4+

Safari

5+

Chrome

5+

Opera

11.5+

Edge

79+

Edge (Legacy)

12+

Internet Explorer

10+

Firefox Android

?

Safari iOS

?

Chrome Android

?

WebView Android

37+

Samsung Internet

?

Opera Android

11.5+

popstate
onrejectionhandled

Window/rejectionhandled_event

Support in all current engines.

Firefox

69+

Safari

11+

Chrome

49+

Opera

?

Edge

79+

Edge (Legacy)

?

Internet Explorer

No

Firefox Android

?

Safari iOS

11.3+

Chrome Android

?

WebView Android

?

Samsung Internet

?

Opera Android

?

rejectionhandled
onstorage

Window/storage_event

Support in all current engines.

Firefox

45+

Safari

4+

Chrome

1+

Opera

?

Edge

79+

Edge (Legacy)

15+

Internet Explorer

9+

Firefox Android

?

Safari iOS

4+

Chrome Android

?

WebView Android

37+

Samsung Internet

?

Opera Android

?

storage
onunhandledrejection

Window/unhandledrejection_event

Support in all current engines.

Firefox

69+

Safari

11+

Chrome

49+

Opera

?

Edge

79+

Edge (Legacy)

?

Internet Explorer

No

Firefox Android

?

Safari iOS

11.3+

Chrome Android

?

WebView Android

?

Samsung Internet

?

Opera Android

?

unhandledrejection
onunload

Window/unload_event

Support in all current engines.

Firefox

1+

Safari

3+

Chrome

1+

Opera

4+

Edge

79+

Edge (Legacy)

12+

Internet Explorer

4+

Firefox Android

?

Safari iOS

1+

Chrome Android

?

WebView Android

?

Samsung Internet

?

Opera Android

10.1+

unload

This list of event handlers is reified as event handler IDL
attributes through the WindowEventHandlers interface mixin.

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

Element/cut_event

Support in all current engines.

Firefox

22+

Safari

3+

Chrome

1+

Opera

12.1+

Edge

79+

Edge (Legacy)

12+

Internet Explorer

9+

Firefox Android

?

Safari iOS

3+

Chrome Android

?

WebView Android

?

Samsung Internet

?

Opera Android

12.1+

cut
oncopy

Element/copy_event

Support in all current engines.

Firefox

22+

Safari

3+

Chrome

1+

Opera

12.1+

Edge

79+

Edge (Legacy)

12+

Internet Explorer

9+

Firefox Android

?

Safari iOS

3+

Chrome Android

?

WebView Android

?

Samsung Internet

?

Opera Android

12.1+

copy
onpaste

Element/paste_event

Support in all current engines.

Firefox

22+

Safari

3+

Chrome

1+

Opera

12.1+

Edge

79+

Edge (Legacy)

12+

Internet Explorer

9+

Firefox Android

?

Safari iOS

3+

Chrome Android

?

WebView Android

37+

Samsung Internet

?

Opera Android

12.1+

paste

This list of event handlers is reified as event handler IDL
attributes through the DocumentAndElementEventHandlers interface mixin.

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
onvisibilitychange

Document/visibilitychange_event

Support in all current engines.

Firefox

56+

Safari

14.1+

Chrome

62+

Opera

49+

Edge

79+

Edge (Legacy)

18

Internet Explorer

🔰 10+

Firefox Android

?

Safari iOS

?

Chrome Android

?

WebView Android

62+

Samsung Internet

?

Opera Android

46+

visibilitychange

8.1.8.2.1

IDL definitions

interface mixin GlobalEventHandlers {
  attribute EventHandler onabort;
  attribute EventHandler onauxclick;
  attribute EventHandler onbeforeinput;
  attribute EventHandler onbeforematch;
  attribute EventHandler onblur;
  attribute EventHandler oncancel;
  attribute EventHandler oncanplay;
  attribute EventHandler oncanplaythrough;
  attribute EventHandler onchange;
  attribute EventHandler onclick;
  attribute EventHandler onclose;
  attribute EventHandler oncontextlost;
  attribute EventHandler oncontextmenu;
  attribute EventHandler oncontextrestored;
  attribute EventHandler oncuechange;
  attribute EventHandler ondblclick;
  attribute EventHandler ondrag;
  attribute EventHandler ondragend;
  attribute EventHandler ondragenter;
  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 onformdata;
  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 onloadstart;
  attribute EventHandler onmousedown;
  [LegacyLenientThis] attribute EventHandler onmouseenter;
  [LegacyLenientThis] attribute EventHandler onmouseleave;
  attribute EventHandler onmousemove;
  attribute EventHandler onmouseout;
  attribute EventHandler onmouseover;
  attribute EventHandler onmouseup;
  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 onscrollend;
  attribute EventHandler onsecuritypolicyviolation;
  attribute EventHandler onseeked;
  attribute EventHandler onseeking;
  attribute EventHandler onselect;
  attribute EventHandler onslotchange;
  attribute EventHandler onstalled;
  attribute EventHandler onsubmit;
  attribute EventHandler onsuspend;
  attribute EventHandler  ;
  attribute EventHandler ontoggle;
  attribute EventHandler onvolumechange;
  attribute EventHandler onwaiting;
  attribute EventHandler onwebkitanimationend;
  attribute EventHandler onwebkitanimationiteration;
  attribute EventHandler onwebkitanimationstart;
  attribute EventHandler onwebkittransitionend;
  attribute EventHandler onwheel;
};

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

  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
pointer 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;
  readonly attribute boolean isSecureContext;
  readonly attribute boolean crossOriginIsolated;

  undefined reportError(any e);

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

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

  // microtask queuing
  undefined queueMicrotask(VoidFunction callback);

  // 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 = {});

  // structured cloning
  any structuredClone(any value, optional StructuredSerializeOptions options = {});
};
Window includes WindowOrWorkerGlobalScope;
WorkerGlobalScope includes WindowOrWorkerGlobalScope;
self.isSecureContext

isSecureContext

Support in all current engines.

Firefox

49+

Safari

11.1+

Chrome

47+

Opera

?

Edge

79+

Edge (Legacy)

15+

Internet Explorer

No

Firefox Android

?

Safari iOS

?

Chrome Android

?

WebView Android

?

Samsung Internet

?

Opera Android

?

Returns whether or not this global object represents a secure context. [SECURE-CONTEXTS]

self.origin

origin

Support in all current engines.

Firefox

54+

Safari

11+

Chrome

59+

Opera

?

Edge

79+

Edge (Legacy)

18

Internet Explorer

No

Firefox Android

?

Safari iOS

?

Chrome Android

?

WebView Android

?

Samsung Internet

?

Opera Android

?

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

self.crossOriginIsolated

crossOriginIsolated

Support in all current engines.

Firefox

72+

Safari

15.2+

Chrome

87+

Opera

?

Edge

87+

Edge (Legacy)

?

Internet Explorer

No

Firefox Android

?

Safari iOS

?

Chrome Android

?

WebView Android

?

Samsung Internet

?

Opera Android

?

Returns whether scripts running in this global are allowed to use APIs that require
cross-origin isolation. This depends on the `Cross-Origin-Opener-Policy` and
`Cross-Origin-Embedder-Policy` HTTP response headers and the “cross-origin-isolated” feature.

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 isSecureContext getter steps are to return true if
this’s relevant settings object is a secure context, or
false otherwise.

The origin getter steps are to return this’s
relevant settings object’s origin, serialized.

The crossOriginIsolated getter steps are to return
this’s relevant settings object’s cross-origin isolated
capability.

8.3

Base64 utility methods

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)

btoa

Support in all current engines.

Firefox

1+

Safari

3+

Chrome

4+

Opera

10.5+

Edge

79+

Edge (Legacy)

12+

Internet Explorer

10+

Firefox Android

?

Safari iOS

1+

Chrome Android

?

WebView Android

37+

Samsung Internet

?

Opera Android

11+

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 “InvalidCharacterErrorDOMException
exception if the input string contains any out-of-range characters.

result = self.atob(data)

atob

Support in all current engines.

Firefox

1+

Safari

3+

Chrome

4+

Opera

10.5+

Edge

79+

Edge (Legacy)

12+

Internet Explorer

10+

Firefox Android

?

Safari iOS

1+

Chrome Android

?

WebView Android

37+

Samsung Internet

?

Opera Android

11+

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 “InvalidCharacterErrorDOMException if the
input string is not valid base64 data.

The btoa(data) method must throw an
InvalidCharacterErrorDOMException 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 steps are:

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

  2. If decodedData is failure, then throw an
    InvalidCharacterErrorDOMException.

  3. Return decodedData.