1. 8 Web application APIs
    1. 8.1 Scripting
      1. 8.1.1 Introduction
      2. 8.1.2 Agents and agent clusters
        1. 8.1.2.1 Integration with the JavaScript agent formalism
        2. 8.1.2.2 Integration with the JavaScript agent cluster formalism
      3. 8.1.3 Realms and their counterparts
        1. 8.1.3.1 Environments
        2. 8.1.3.2 Environment settings objects
        3. 8.1.3.3 Realms, settings objects, and global objects
          1. 8.1.3.3.1 Entry
          2. 8.1.3.3.2 Incumbent
          3. 8.1.3.3.3 Current
          4. 8.1.3.3.4 Relevant
        4. 8.1.3.4 Enabling and disabling scripting
        5. 8.1.3.5 Secure contexts
      4. 8.1.4 Script processing model
        1. 8.1.4.1 Scripts
        2. 8.1.4.2 Fetching scripts
        3. 8.1.4.3 Creating scripts
        4. 8.1.4.4 Calling scripts
        5. 8.1.4.5 Killing scripts
        6. 8.1.4.6 Runtime script errors
        7. 8.1.4.7 Unhandled promise rejections
        8. 8.1.4.8 Import map parse results
      5. 8.1.5 Module specifier resolution
        1. 8.1.5.1 The resolution algorithm
        2. 8.1.5.2 Import maps
        3. 8.1.5.3 Import map processing model
      6. 8.1.6 JavaScript specification host hooks
        1. 8.1.6.1 HostEnsureCanAddPrivateElement(O)
        2. 8.1.6.2 HostEnsureCanCompileStrings(realm, parameterStrings, bodyString, codeString, compilationType, parameterArgs, bodyArg)
        3. 8.1.6.3 HostGetCodeForEval(argument)
        4. 8.1.6.4 HostPromiseRejectionTracker(promise, operation)
        5. 8.1.6.5 HostSystemUTCEpochNanoseconds(global)
        6. 8.1.6.6 Job-related host hooks
          1. 8.1.6.6.1 HostCallJobCallback(callback, V, argumentsList)
          2. 8.1.6.6.2 HostEnqueueFinalizationRegistryCleanupJob(finalizationRegistry)
          3. 8.1.6.6.3 HostEnqueueGenericJob(job, realm)
          4. 8.1.6.6.4 HostEnqueuePromiseJob(job, realm)
          5. 8.1.6.6.5 HostEnqueueTimeoutJob(job, realm, milliseconds)
          6. 8.1.6.6.6 HostMakeJobCallback(callable)
        7. 8.1.6.7 Module-related host hooks
          1. 8.1.6.7.1 HostGetImportMetaProperties(moduleRecord)
          2. 8.1.6.7.2 HostGetSupportedImportAttributes()
          3. 8.1.6.7.3 HostLoadImportedModule(referrer, moduleRequest, loadState, payload)
      7. 8.1.7 Event loops
        1. 8.1.7.1 Definitions
        2. 8.1.7.2 Queuing tasks
        3. 8.1.7.3 Processing model
        4. 8.1.7.4 Generic task sources
        5. 8.1.7.5 Dealing with the event loop from other specifications
      8. 8.1.8 Events
        1. 8.1.8.1 Event handlers
        2. 8.1.8.2 Event handlers on elements, Document objects, and Window objects
          1. 8.1.8.2.1 IDL definitions
        3. 8.1.8.3 Event firing
    2. 8.2 The WindowOrWorkerGlobalScope mixin
    3. 8.3 Base64 utility methods

8 Web application APIs

8.1 Scripting

8.1.1 Introduction

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

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

Similar-origin window agent

Contains various Window objects which can potentially reach each other, either directly or by using document.domain.

If the encompassing agent cluster's is origin-keyed is true, then all the Window objects will be same origin, can reach each other directly, and document.domain will no-op.

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

Dedicated worker agent

Contains a single DedicatedWorkerGlobalScope.

Shared worker agent

Contains a single SharedWorkerGlobalScope.

Service worker agent

Contains a single ServiceWorkerGlobalScope.

Worklet agent

Contains a single WorkletGlobalScope object.

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

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

  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.

For a realm realm, the agent whose [[Signifier]] is realm.[[AgentSignifier]] is the realm's agent.

The relevant agent for a platform object platformObject is platformObject's relevant realm's agent.

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:

  1. Let site be the result of obtaining a site with origin.

  2. Let key be site.

  3. If group's cross-origin isolation mode is not "none", then set key to origin.

  4. Otherwise, if group's historical agent cluster key map[origin] exists, then set key to group's historical agent cluster key map[origin].

  5. Otherwise:

    1. If requestsOAC is true, then set key to origin.

    2. Set group's historical agent cluster key map[origin] to key.

  6. If group's agent cluster map[key] does not exist, then:

    1. Let agentCluster be a new agent cluster.

    2. Set agentCluster's cross-origin isolation mode to group's cross-origin isolation mode.

    3. If key is an origin:

      1. Assert: key is origin.

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

    4. Add the result of creating an agent, given false, to agentCluster.

    5. Set group's agent cluster map[key] to agentCluster.

  7. Return the single similar-origin window agent contained in group's agent cluster map[key].

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:

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

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 (i.e., a navigation params's reserved environment or a request's reserved client). An environment has the following fields:

An id

An opaque string that uniquely identifies this environment.

A creation URL

A URL that represents the location of the resource with which this environment is associated.

In the case of a Window environment settings object, this URL might be distinct from its global object's associated Document's URL, due to mechanisms such as history.pushState() which modify the latter.

A top-level creation URL

Null or a URL that represents the creation URL of the "top-level" environment. It is null for workers and worklets.

A top-level origin

A for now implementation-defined value, null, or an origin. For a "top-level" potential execution environment it is null (i.e., when there is no response yet); otherwise it is the "top-level" environment's origin. For a dedicated worker or worklet it is the top-level origin of its creator. For a shared or service worker it is an implementation-defined value.

This is distinct from the top-level creation URL's origin when sandboxing, workers, and worklets are involved.

A target browsing context

Null or a target browsing context for a navigation request.

An active service worker

Null or a service worker that controls the environment.

An execution ready flag

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

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

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

8.1.3.2 Environment settings objects

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

A realm execution context

A JavaScript execution context shared by all scripts that use this settings object, i.e., all scripts in a given realm. When we run a classic script or run a module script, this execution context becomes the top of the JavaScript execution context stack, on top of which another execution context specific to the script in question is pushed. (This setup ensures Source Text Module Record's Evaluate knows which realm to use.)

A module map

A module map that is used when importing JavaScript modules.

An API base URL

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

An origin

An origin used in security checks.

A has cross-site ancestor

A boolean used in security checks.

A policy container

A policy container containing policies used for security checks.

A cross-origin isolated capability

A boolean representing whether scripts that use this environment settings object are allowed to use APIs that require cross-origin isolation.

A time origin
A number used as the baseline for performance-related timestamps. [HRT]

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, WorkerGlobalScope, or WorkletGlobalScope objects.

A global object has an in error reporting mode boolean, which is initially false.

A global object has an outstanding rejected promises weak set, a set of Promise objects, initially empty. This set must not create strong references to any of its members, and implementations are free to limit its size in an implementation-defined manner, e.g., by removing old entries from it when new ones are added.

A global object has an about-to-be-notified rejected promises list, a list of Promise objects, initially empty.

A global object has an import map, initially an empty import map.

For now, only Window global objects have their import map modified from the initial empty one. The import map is only accessed for the resolution of a root module script.

A global object has a resolved module set, a set of specifier resolution records, initially empty.

The resolved module set ensures that module specifier resolution returns the same result when called multiple times with the same (referrer, specifier) pair. It does that by ensuring that import map rules that impact the specifier in its referrer's scope cannot be defined after its initial resolution. For now, only Window global objects have their module set data structures modified from the initial empty one.


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:

  1. Perform InitializeHostDefinedRealm() with the provided customizations for creating the global object and the global this binding.

  2. Let realm execution context be the running JavaScript execution context.

    This is the JavaScript execution context created in the previous step.

  3. Remove realm execution context from the JavaScript execution context stack.

  4. Let realm be realm execution context's Realm component.

  5. If agent's agent cluster's cross-origin isolation mode is "none", then:

    1. Let global be realm's global object.

    2. Let status be ! global.[[Delete]]("SharedArrayBuffer").

    3. Assert: status is true.

    This is done for compatibility with web content and there is some hope that this can be removed in the future. Web developers can still get at the constructor through new WebAssembly.Memory({ shared:true, initial:0, maximum:0 }).buffer.constructor.

  6. Return realm execution context.


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:

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:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

Consider the following starter example:

<!DOCTYPE html>
<iframe></iframe>
<script>
  frames[0].postMessage("some data", "*");
</script>

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

It should be that of window, to capture the intuitive notion that the author script responsible for causing the algorithm to happen is executing in window, not frames[0]. This makes sense: the window post message steps use the incumbent settings object to determine the source property of the resulting MessageEvent, and in this case window is definitely the source of the message.

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

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

(Note how the environment settings object of frames[0] is the relevant settings object of this at the time the postMessage() method is called, and thus is involved in determining the target of the message. Whereas the incumbent is used to determine the source.)

Consider the following more complicated example:

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

This example is very similar to the previous one, but with an extra indirection through Function.prototype.bind as well as setTimeout(). But, the answer should be the same: invoking algorithms asynchronously should not change the incumbent concept.

This time, the result involves more complicated mechanisms:

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

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

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

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

Consider this final, even more convoluted example:

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

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

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

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

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

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

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

  1. If environment is an environment settings object, then:

    1. Let global be environment's global object.

    2. If global is a WorkerGlobalScope, then:

      1. If global's owner set[0]'s relevant settings object is a secure context, then return true.

        We only need to check the 0th item since they will necessarily all be consistent.

      2. Return false.

    3. If global is a WorkletGlobalScope, then return true.

      Worklets can only be created in secure contexts.

  2. If the result of Is url potentially trustworthy? given environment's top-level creation URL is "Potentially Trustworthy", then return true.

  3. Return false.

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 two possible structs (namely, a classic script or a module script). All scripts have:

A settings object

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

A record

One of the following:

A parse error

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

This value is used for internal tracking of immediate parse errors when creating scripts, and is not to be used directly. Instead, consult the error to rethrow when determining "what went wrong" for this script.

An error to rethrow

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

This could be the script's parse error, but in the case of a module script it could instead be the parse error from one of its dependencies, or an error from resolve a module specifier.

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

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

Null or a base URL used for resolving module specifiers. When non-null, this will either be the URL from which the script was obtained, for external scripts, or the document base URL of the containing document, for inline scripts.

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

A muted errors boolean

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

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

Module scripts can be classified into four 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

This policy can mutate after a module script's response is received, to be the referrer policy parsed from the response, and used when fetching any module dependencies.

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.

fetch priority

The priority used for the initial fetch

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

The default 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", referrer policy is the empty string, and fetch priority is "auto".

To set up the classic script request, given a request request and a script fetch options options, set request's cryptographic nonce metadata to options's cryptographic nonce, its integrity metadata to options's integrity metadata, its parser metadata to options's parser metadata, its referrer policy to options's referrer policy, its render-blocking to options's render-blocking, and its priority to options's fetch priority.

To set up the module script request, given a request request and a script fetch options options, set request's cryptographic nonce metadata to options's cryptographic nonce, its integrity metadata to options's integrity metadata, its parser metadata to options's parser metadata, its credentials mode to options's credentials mode, its referrer policy to options's referrer policy, its render-blocking to options's render-blocking, and its priority to options's fetch priority.

To get the descendant script fetch options given a script fetch options originalOptions, a URL url, and an environment settings object settingsObject:

  1. Let newOptions be a copy of originalOptions.

  2. Let integrity be the result of resolving a module integrity metadata with url and settingsObject.

  3. Set newOptions's integrity metadata to integrity.

  4. Set newOptions's fetch priority to "auto".

  5. Return newOptions.

To resolve a module integrity metadata, given a URL url and an environment settings object settingsObject:

  1. Let map be settingsObject's global object's import map.

  2. If map's integrity[url] does not exist, then return the empty string.

  3. Return map's integrity[url].


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 or fetching a module worker script graph, but false for the fetches resulting from import statements encountered throughout the graph or from import() expressions.

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 url, an environment settings object settingsObject, a script fetch options options, a CORS settings attribute state corsSetting, an encoding encoding, and an algorithm onComplete, run these steps. onComplete must be an algorithm accepting null (on failure) or a classic script (on success).

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

  2. Set request's client to settingsObject.

  3. Set request's initiator type to "script".

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

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

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

    1. Set response to response's unsafe response.

    2. If any of the following are true:

      then run onComplete given null, and abort these steps.

      For historical reasons, this algorithm does not include MIME type checking, unlike the other script-fetching algorithms in this section.

    3. Let potentialMIMETypeForEncoding be the result of extracting a MIME type given response's header list.

    4. Set encoding to the result of legacy extracting an encoding given potentialMIMETypeForEncoding and encoding.

      This intentionally ignores the MIME type essence.

    5. Let sourceText be the result of decoding bodyBytes to Unicode, using encoding as the fallback encoding.

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

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

    7. Let script be the result of creating a classic script given sourceText, settingsObject, response's URL, options, mutedErrors, and url.

    8. Run onComplete given script.

To fetch a classic worker script given a URL url, an environment settings object fetchClient, a destination destination, an environment settings object settingsObject, an algorithm onComplete, 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).

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

  2. If performFetch was given, run performFetch with request, true, and with processResponseConsumeBody as defined below.

    Otherwise, fetch request with processResponseConsumeBody set to processResponseConsumeBody as defined below.

    In both cases, let processResponseConsumeBody given response response and null, failure, or a byte sequence bodyBytes be the following algorithm:

    1. Set response to response's unsafe response.

    2. If any of the following are true:

      then run onComplete given null, and abort these steps.

    3. If all of the following are true:

      then run onComplete given null, and abort these steps.

      Other fetch schemes are exempted from MIME type checking for historical web-compatibility reasons. We might be able to tighten this in the future; see issue #3255.

    4. Let sourceText be the result of UTF-8 decoding bodyBytes.

    5. Let script be the result of creating a classic script using sourceText, settingsObject, response's URL, and the default script fetch options.

    6. Run onComplete given script.

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

  1. Let response be null.

  2. Let bodyBytes be null.

  3. Let request be a new request whose URL is url, client is settingsObject, destination is "script", initiator type is "other", parser metadata is "not parser-inserted", and whose use-URL-credentials flag is set.

  4. If performFetch was given, run performFetch with request, isTopLevel, and with processResponseConsumeBody as defined below.

    Otherwise, fetch request with processResponseConsumeBody set to processResponseConsumeBody as defined below.

    In both cases, let processResponseConsumeBody given response res and null, failure, or a byte sequence bb be the following algorithm:

    1. Set bodyBytes to bb.

    2. Set response to res.

  5. Pause until response is not null.

    Unlike other algorithms in this section, the fetching process is synchronous here.

  6. Set response to response's unsafe response.

  7. If any of the following are true:

    then throw a "NetworkError" DOMException.

  8. Let sourceText be the result of UTF-8 decoding bodyBytes.

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

  10. Let script be the result of creating a classic script given sourceText, settingsObject, response's URL, the default script fetch options, and mutedErrors.

  11. Return script.

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

  1. Fetch a single module script given url, settingsObject, "script", options, settingsObject, "client", true, and with the following steps given result:

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

    2. Fetch the descendants of and link result given settingsObject, "script", and onComplete.

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

  1. Fetch a single module script given url, settingsObject, destination, options, settingsObject, "client", true, and with the following steps given result:

    1. Run onComplete given result.

    2. Assert: settingsObject's global object implements Window.

    3. If result is not null, optionally fetch the descendants of and link result given settingsObject, destination, and an empty algorithm.

      Generally, performing this step 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 string sourceText, a URL baseURL, an environment settings object settingsObject, a script fetch options options, and an algorithm onComplete, run these steps. onComplete must be an algorithm accepting null (on failure) or a module script (on success).

  1. Let script be the result of creating a JavaScript module script using sourceText, settingsObject, baseURL, and options.

  2. Fetch the descendants of and link script, given settingsObject, "script", and onComplete.

To fetch a module worker script graph given a URL url, an environment settings object fetchClient, a destination destination, a credentials mode credentialsMode, an environment settings object settingsObject, and an algorithm onComplete, fetch a worklet/module worker script graph given url, fetchClient, destination, credentialsMode, settingsObject, and onComplete.

To fetch a worklet script graph given a URL url, an environment settings object fetchClient, a destination destination, a credentials mode credentialsMode, an environment settings object settingsObject, a module responses map moduleResponsesMap, and an algorithm onComplete, fetch a worklet/module worker script graph given url, fetchClient, destination, credentialsMode, settingsObject, 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:

fetch an external module script graph fetch a modulepreload module script graph fetch an inline module script graph fetch a module worker script graph fetch a worklet script graph fetch a worklet/module worker script graph fetch the descendants of and link a module script

To fetch a worklet/module worker script graph given a URL url, an environment settings object fetchClient, a destination destination, a credentials mode credentialsMode, an environment settings object settingsObject, an algorithm onComplete, 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. Let options be a script fetch options whose cryptographic nonce is the empty string, integrity metadata is the empty string, parser metadata is "not-parser-inserted", credentials mode is credentialsMode, referrer policy is the empty string, and fetch priority is "auto".

  2. Fetch a single module script given url, fetchClient, destination, options, settingsObject, "client", true, and onSingleFetchComplete as defined below. If performFetch was given, pass it along as well.

    onSingleFetchComplete given result is the following algorithm:

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

    2. Fetch the descendants of and link result given fetchClient, destination, and onComplete. If performFetch was given, pass it along as well.

To fetch the descendants of and link a module script moduleScript, given an environment settings object fetchClient, a destination destination, an algorithm onComplete, 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. Let record be moduleScript's record.

  2. If record is null, then:

    1. Set moduleScript's error to rethrow to moduleScript's parse error.

    2. Run onComplete given moduleScript.

    3. Return.

  3. Let state be Record { [[ErrorToRethrow]]: null, [[Destination]]: destination, [[PerformFetch]]: null, [[FetchClient]]: fetchClient }.

  4. If performFetch was given, set state.[[PerformFetch]] to performFetch.

  5. Let loadingPromise be record.LoadRequestedModules(state).

    This step will recursively load all the module transitive dependencies.

  6. Upon fulfillment of loadingPromise, run the following steps:

    1. Perform record.Link().

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

      If this throws an exception, catch it, and set moduleScript's error to rethrow to that exception.

    2. Run onComplete given moduleScript.

  7. Upon rejection of loadingPromise, run the following steps:

    1. If state.[[ErrorToRethrow]] is not null, set moduleScript's error to rethrow to state.[[ErrorToRethrow]] and run onComplete given moduleScript.

    2. Otherwise, run onComplete given null.

      state.[[ErrorToRethrow]] is null when loadingPromise is rejected due to a loading error.

To fetch a single module script, given a URL url, an environment settings object fetchClient, a destination destination, a script fetch options options, an environment settings object settingsObject, a referrer referrer, an optional ModuleRequest Record moduleRequest, a boolean isTopLevel, an algorithm onComplete, 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. Let moduleType be "javascript-or-wasm".

  2. If moduleRequest was given, then set moduleType to the result of running the module type from module request steps given moduleRequest.

  3. Assert: the result of running the module type allowed steps given moduleType and settingsObject is true. Otherwise, we would not have reached this point because a failure would have been raised when inspecting moduleRequest.[[Attributes]] in HostLoadImportedModule or fetch a single imported module script.

  4. Let moduleMap be settingsObject's module map.

  5. If moduleMap[(url, moduleType)] 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.

  6. If moduleMap[(url, moduleType)] exists, run onComplete given moduleMap[(url, moduleType)], and return.

  7. Set moduleMap[(url, moduleType)] to "fetching".

  8. Let request be a new request whose URL is url, mode is "cors", referrer is referrer, and client is fetchClient.

  9. Set request's destination to the result of running the fetch destination from module type steps given destination and moduleType.

  10. If destination is "worker", "sharedworker", or "serviceworker", and isTopLevel is true, then set request's mode to "same-origin".

  11. Set request's initiator type to "script".

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

  13. If performFetch was given, run performFetch with request, isTopLevel, and with processResponseConsumeBody as defined below.

    Otherwise, fetch request with processResponseConsumeBody set to processResponseConsumeBody as defined below.

    In both cases, let processResponseConsumeBody given response response and null, failure, or a byte sequence bodyBytes be the following algorithm:

    response is always CORS-same-origin.

    1. If any of the following are true:

      then set moduleMap[(url, moduleType)] to null, run onComplete given null, and abort these steps.

    2. Let mimeType be the result of extracting a MIME type from response's header list.

    3. Let moduleScript be null.

    4. Let referrerPolicy be the result of parsing the `Referrer-Policy` header given response. [REFERRERPOLICY]

    5. If referrerPolicy is not the empty string, set options's referrer policy to referrerPolicy.

    6. If mimeType's essence is "application/wasm" and moduleType is "javascript-or-wasm", then set moduleScript to the result of creating a WebAssembly module script given bodyBytes, settingsObject, response's URL, and options.

    7. Otherwise:

      1. Let sourceText be the result of UTF-8 decoding bodyBytes.

      2. If mimeType is a JavaScript MIME type and moduleType is "javascript-or-wasm", then set moduleScript to the result of creating a JavaScript module script given sourceText, settingsObject, response's URL, and options.

      3. If the MIME type essence of mimeType is "text/css" and moduleType is "css", then set moduleScript to the result of creating a CSS module script given sourceText and settingsObject.

      4. If mimeType is a JSON MIME type and moduleType is "json", then set moduleScript to the result of creating a JSON module script given sourceText and settingsObject.

    8. Set moduleMap[(url, moduleType)] to moduleScript, and run onComplete given moduleScript.

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

To fetch a single imported module script, given a URL url, an environment settings object fetchClient, a destination destination, a script fetch options options, environment settings object settingsObject, a referrer referrer, a ModuleRequest Record moduleRequest, an algorithm onComplete, 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. Assert: moduleRequest.[[Attributes]] does not contain any Record entry such that entry.[[Key]] is not "type", because we only asked for "type" attributes in HostGetSupportedImportAttributes.

  2. Let moduleType be the result of running the module type from module request steps given moduleRequest.

  3. If the result of running the module type allowed steps given moduleType and settingsObject is false, then run onComplete given null, and return.

  4. Fetch a single module script given url, fetchClient, destination, options, settingsObject, referrer, moduleRequest, false, and onComplete. If performFetch was given, pass it along as well.

8.1.4.3 Creating scripts

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

  1. If mutedErrors is true, then set baseURL to about:blank.

    When mutedErrors is true, baseURL is the script's CORS-cross-origin response's url, which shouldn't be exposed to JavaScript. Therefore, baseURL is sanitized here.

  2. If scripting is disabled for settings, then set source to the empty string.

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

  4. Set script's settings object to settings.

  5. Set script's base URL to baseURL.

  6. Set script's fetch options to options.

  7. Set script's muted errors to mutedErrors.

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

  9. Record classic script creation time given script and sourceURLForWindowScripts.

  10. Let result be ParseScript(source, settings's realm, script).

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

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

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

    2. Return script.

  12. Set script's record to result.

  13. Return script.

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

  1. If scripting is disabled for settings, then set source to the empty string.

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

  3. Set script's settings object to settings.

  4. Set script's base URL to baseURL.

  5. Set script's