Processing of technologies like SVG that have their own scripting features.

7.1.2. Enabling and disabling scripting

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

The user agent supports scripting.

The user has not disabled scripting for this browsing context at this time.
(User agents may provide users with the option to disable scripting globally, or in a
finer-grained manner, e.g. on a per-origin basis.)

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

7.1.3.2. Fetching scripts

The various script-fetching algorithms below have two hooks that may be customized by their
callers:

Set up the request, which takes a request which it may modify before the
algorithm continues

Process the response, which takes a response and must either return true or false to indicate success or failure, respectively

Service Workers is an example of a specification that runs these algorithms with
its own options for the hooks. [SERVICE-WORKERS]

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

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

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

If ancestor list is not given, let it be an empty list.

If module map settings object is not given, let it be fetch client settings
object.

The following algorithms are used when fetching a module script tree, and are not meant to
be used directly by other specifications (or by other parts of this specification).

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

If any of the fetch a module script tree invocations asynchronously complete with
null, the user agent may terminate any or all of the other fetches, and must then
asynchronously complete this algorithm with null.

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

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

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

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

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

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.

In general, the current concept is what should be used by specifications going forward.
There is an important exception, however. If an algorithm is creating an object that is to be
persisted and returned multiple times (instead of simply returned to author code right away, and
never vended again), it should use the relevant concept with regard to the object on which
the method in question is being executed. This prevents cross-realm calls from causing an object
to store objects created in the "wrong" realm.

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

7.1.3.5.1. Entry

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

User agents may impose resource limitations on scripts, for example CPU quotas, memory limits,
total execution time limits, or bandwidth limitations. When a script exceeds a limit, the user
agent may either throw a QuotaExceededError exception, 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.

7.1.3.7. Integration with the JavaScript job queue

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

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

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

7.1.3.8. Integration with the JavaScript module system

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

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

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

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

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

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

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

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

7.1.3.9. Runtime script errors

When the user agent is required to report an error for a
particular scriptscript 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:

Let message be a user-agent-defined string describing the error in a helpful manner.

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

Let location be an absolute URL that corresponds to the resource from which script was obtained.

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

7.1.3.9.1. Runtime script errors in documents

When the user agent is to report an exceptionE, 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 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 absolute URL of the script in which the error
originally occurred.

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

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

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

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.

7.1.4. Event loops

7.1.4.1. Definitions

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

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

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

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

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

7.1.4.2. Processing model

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

There are many factors that affect the ideal update frequency for the top-level
browsing context including performance, power, background operation, quality of
user experience, refresh rate of display(s), etc. When in foreground and not
constrained by resources (i.e. performance, battery versus mains power, other resource
limits), the user agent normally prioritizes for maximum quality of user
experience for that set of Documents by matching update frequency and animation frame callback rate to the
current refresh rate of the current display (usually 60Hz, but refresh rate may be
higher or lower). When accommodating constraints on resources, the update frequency
might automatically run at a lower rate. Also, if a top-level browsing context is in the background, the user agent might decide to drop that page to a much slower
4Hz, or even less.

Another example of why a browser might skip updating the rendering is to ensure certain tasks are executed immediately after each other, with only microtask checkpoints interleaved (and without, e.g., animation frame callbacks interleaved).
For example, a user agent might wish to coalesce callbacks together, with no
intermediate rendering updates. However, when are no constraints on resources,
there must not be an arbitrary permanent user agent limit on the update rate and animation frame callback rate
(i.e., high refresh rate displays and/or low latency applications).

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

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

Run the algorithm’s synchronous section.

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

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.

7.1.4.3. Generic task sources

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

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

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

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

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

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

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

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

7.1.5.3. Event firing

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

Firing a simple event named e means that a trusted event with the name e, which does not
bubble (except where otherwise stated) and is not cancelable (except where otherwise stated), and
which uses the Event interface, must be created and dispatched at the given target.

Firing a synthetic mouse event named e means that an event with the name e, which is trusted (except where otherwise
stated), does not bubble (except where otherwise stated), is not cancelable (except where
otherwise stated), and which uses the MouseEvent interface, must be created and dispatched at
the given target. The event object must have its screenX, screenY, clientX, clientY, and button attributes initialized to
0, its ctrlKey, shiftKey, altKey, and metaKey attributes initialized according to the current state of the key input
device, if any (false for any keys that are not available), its detail attribute
initialized to 1, its relatedTarget attribute initialized to null (except where
otherwise stated), and its view attribute initialized to the Window object of
the Document object of the given target node, if any, or else null. The getModifierState() method on the object must return values appropriately describing
the state of the key input device at the time the event is created.

The default action of these events is to do nothing except where otherwise stated.

7.1.5.4. Events and the Window object

When an event is dispatched at a DOM node in a Document in a browsing
context, if the event is not a load event, the user agent
must act as if, for the purposes of event dispatching,
the Window object is the parent of the Document object. [DOM41]

7.3. Base64 utility methods

The atob() and btoa() methods allow authors 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 = window . btoa( data )

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

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.

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

The atob() method must run the following
steps to parse the string passed in the method’s first argument:

Let input be the string being parsed.

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

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

While position does not point past the end of input,
run these substeps:

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

Character

Number

A

0

B

1

C

2

D

3

E

4

F

5

G

6

H

7

I

8

J

9

K

10

L

11

M

12

N

13

O

14

P

15

Q

16

R

17

S

18

T

19

U

20

V

21

W

22

X

23

Y

24

Z

25

a

26

b

27

c

28

d

29

e

30

f

31

g

32

h

33

i

34

j

35

k

36

l

37

m

38

n

39

o

40

p

41

q

42

r

43

s

44

t

45

u

46

v

47

w

48

x

49

y

50

z

51

0

52

1

53

2

54

3

55

4

56

5

57

6

58

7

59

8

60

9

61

+

62

/

63

Append to buffer the six bits corresponding to number, most significant bit first.

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

Advance position by one character.

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

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

7.4.1. Opening the input stream

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

window . clearInterval( handle )

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

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

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

Objects that implement the WindowTimers interface have a list of active
timers. Each entry in this lists is identified by a number, which must be unique within the
list for the lifetime of the object that implements the WindowTimers interface.

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

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

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

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

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

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

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

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

Let timeout be the second method argument.

If the currently running task is a task that was created
by this algorithm, then let nesting level be the task’s timer nesting level. Otherwise, let nesting level be zero.

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

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

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

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

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

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

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

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

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

function doExpensiveWork(){var done =false;// ...// this part of the function takes up to five milliseconds// set done to true if we’re done// ...return done;}function rescheduleWork(){var handle = setTimeout(rescheduleWork,0);// preschedule next iterationif(doExpensiveWork())
clearTimeout(handle);// clear the timeout if we don’t need it}function scheduleWork(){
setTimeout(rescheduleWork,0);}
scheduleWork();// queues a task to do lots of work

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

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

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

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

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

The printing steps are as follows:

The user agent may display a message to the user or abort these steps (or both).

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

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

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

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

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

7.7. System state and capabilities

7.7.1. The Navigator object

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

Must return the string used for the value of the "User-Agent" header
in HTTP requests, or the empty string if no such header is ever sent.

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

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

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

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

Any information in this API that varies from user to user can be used to profile or identify
the user.

If the user is not using a service that obfuscates the user’s point of origin (e.g., the Tor
anonymity network), then the value that is least likely to distinguish the user from other users
with similar origins (e.g., from the same IP address block) is the language used by the majority
of such users. [TOR]

If the user is using an anonymizing service, then the value "en-US" is
suggested; if all users of the service use that same value, that reduces the possibility of
distinguishing the users from each other.

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

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

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

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

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

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

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

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

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

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

scheme (registerProtocolHandler() only)

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

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

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

The following schemes are the safelisted schemes:

bitcoin

geo

im

irc

ircs

magnet

mailto

mms

news

nntp

openpgp4fpr

sip

sms

smsto

ssh

tel

urn

webcal

wtai

xmpp

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

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

mimeType (registerContentHandler() only)

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

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

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

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

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

When the user agent uses this handler, it must replace the first occurrence of the exact
literal string "%s" in the url argument with an
escaped version of the absolute URL of the content in question (as defined below),
then parse the resulting URL, relative to the API
base URL specified by the entry settings object at the time the registerContentHandler() or registerProtocolHandler() methods were
invoked, and then navigate an appropriate browsing
context to the resulting URL.

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

title

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

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

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

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

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

new

Indicates that no attempt has been made to register the given handler (or that the handler
has been unregistered). It would be appropriate to promote the availability of the handler or
to just automatically register the handler.

registered

Indicates that the given handler has been registered or that the site is blocked from
registering the handler. Trying to register the handler again would have no effect.

declined

Indicates that the given handler has been offered but was rejected. Trying to register the
handler again may prompt the user again.

window . navigator . unregisterProtocolHandler(scheme, url)

window . navigator . unregisterContentHandler(mimeType, url)

Unregisters the handler given by the arguments.

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

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

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

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

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

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

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

new

The described handler has never been registered for the given scheme or type.

The described handler was once registered for the given scheme or type, but the site has
since unregistered it. If the handler were to be reregistered, the user would be notified
accordingly.

The described handler was once registered for the given scheme or type, but the site has
since unregistered it, but the user has indicated that the site is to be blocked from registering
the type again, so the user agent would ignore further registration attempts.

registered

An attempt was made to register the described handler for the given scheme or type, but the
user has not yet been notified, and the user agent would ignore further registration attempts.
(Maybe the user agent batches registration requests to display them when the user requests to be
notified about them, and the user has not yet requested that the user agent notify it of the
previous registration attempt.)

The described handler is registered for the given scheme or type (maybe, or maybe not, as the
default handler).

The described handler is permanently blocked from being (re)registered. (Maybe the user
marked the registration attempt as spam, or blocked the site for other reasons.)

declined

An attempt was made to register the described handler for the given scheme or type, but the
user has not yet been notified; however, the user might be notified if another registration
attempt were to be made. (Maybe the last registration attempt was made while the page was in the
background and the user closed the page without looking at it, and the user agent requires
confirmation for this registration attempt.)

An attempt was made to register the described handler for the given scheme or type, but the
user has not yet responded.

An attempt was made to register the described handler for the given scheme or type, but the
user declined the offer. The user has not indicated that the handler is to be permanently
blocked, however, so another attempt to register the described handler might result in the user
being prompted again.

The described handler was once registered for the given scheme or type, but the user has
since removed it. The user has not indicated that the handler is to be permanently blocked,
however, so another attempt to register the described handler might result in the user being
prompted again.

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

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

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

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

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

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

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

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

7.7.1.3.1. Security and privacy

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

Hijacking all Web usage. User agents should not allow schemes that are key to
its normal operation, such as http or https, to be
rerouted through third-party sites. This would allow a user’s activities to be trivially tracked,
and would allow user information, even in secure connections, to be collected.

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

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

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

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

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

The user registers a third-party content handler as the default handler for a content
type.

The user then browses his corporate Intranet site and accesses a document that uses that
content type.

The user agent contacts the third party and hands the third party the URL to the Intranet
content.

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

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

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

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

7.7.1.3.2. Sample user interface

This section is non-normative.

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

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

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

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

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

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

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

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

An ImageBitmap object represents a bitmap image that can be painted to a canvas
without undue latency.

The exact judgement of what is undue latency of this is left up to the
implementer, but in general if making use of the bitmap requires network I/O, or even local disk
I/O, then the latency is probably undue; whereas if it only requires a blocking read from a GPU or
system RAM, the latency is probably acceptable.

promise = Window . createImageBitmap(image [, sx, sy, sw, sh ] )

Takes image, which can be an img element, video, or canvas element, a Blob object, an ImageData object, a CanvasRenderingContext2D object, or another ImageBitmap object, and returns a promise that is resolved when a new ImageBitmap is created.

If no ImageBitmap object can be constructed, for example because the provided image data is not actually an image, then the promise is rejected instead.

If sx, sy, sw, and sh arguments are provided, the source image is cropped to the given pixels, with
any pixels missing in the original replaced by transparent black. These coordinates are in the
source image’s pixel coordinate space, not in CSS pixels.

Rejects the promise with an InvalidStateError exception if the source image is not in a valid
state (e.g., an img element that hasn’t finished loading, or a CanvasRenderingContext2D object whose bitmap data has zero length along one or both
dimensions, or an ImageData object whose data is data attribute has been neutered). Rejects the promise with a "SyntaxError" DOMException if the script is not allowed to access the image data of the source image (e.g., a video that is CORS-cross-origin, or a canvas being drawn
on by a script in a worker from another origin).

An ImageBitmap object always has associated bitmap data, with a width and a height.
However, it is possible for this data to be corrupted. If an ImageBitmap object’s
media data can be decoded without errors, it is said to be fully decodable.

An ImageBitmap object’s bitmap has an origin-clean flag, which indicates whether the
bitmap is tainted by content from a different origin. The flag is initially set to
true and may be changed to false by the steps of createImageBitmap().

If the img element’s media data is not a bitmap (e.g., it’s a vector
graphic), then return a promise rejected with an InvalidStateError exception and abort these
steps.

Create a new ImageBitmap object.

Let the ImageBitmap object’s bitmap data be a copy of the img element’s media data, cropped to the source rectangle. If this is an animated
image, the ImageBitmap object’s bitmap data must only be taken from the default
image of the animation (the one that the format defines is to be used when animation is not
supported or is disabled), or, if there is no such image, the first frame of the
animation.

Apply the image sniffing rules to
determine the file format of the image data, with MIME type of the Blob (as given
by the Blob object’s type attribute) giving the
official type.

If the image data is not in a supported file format (e.g., it’s not actually an image at
all), or if the image data is corrupted in some fatal way such that the image dimensions cannot
be obtained, then reject the promise with null, and abort these steps.

Create a new ImageBitmap object.

Let the ImageBitmap object’s bitmap data be the image data read from the Blob object, cropped to the source rectangle. If this is an animated
image, the ImageBitmap object’s bitmap data must only be taken from the default
image of the animation (the one that the format defines is to be used when animation is not
supported or is disabled), or, if there is no such image, the first frame of the
animation.

Resolve the promise with the new ImageBitmap object as the value.

If image is an ImageData object

If either the sw or sh arguments are specified
but zero, return a promise rejected with an IndexSizeError exception and abort these steps.

If the image object’s data attribute has been neutered, return a promise rejected with an InvalidStateError exception and abort these steps.

If either the sw or sh arguments are specified
but zero, return a promise rejected with an IndexSizeError exception and abort these steps.

If the CanvasRenderingContext2D object’s scratch bitmap has
either a horizontal dimension or a vertical dimension equal to zero, then return a promise rejected with an InvalidStateError exception and abort these steps.

When the steps above require that the user agent crop bitmap data to the source rectangle, the user agent must run the following
steps:

Let input be the image data being cropped.

If the sx, sy, sw, and sh arguments are omitted, return input.

Place input on an infinite transparent black grid plane, positioned so
that it’s top left corner is at the origin of the plane, with the x-coordinate increasing to the right, and the y-coordinate
increasing down, and with each pixel in the input image data occupying a cell
on the plane’s grid.

Let output be the rectangle on the plane denoted by the rectangle whose
corners are the four points (sx, sy), (sx+sw, sy), (sx+sw, sy+sh), (sx, sy+sh).

If either sw or sh are negative, then
the top-left corner of this rectangle will be to the left or above the (sx, sy) point. If any of the pixels on this rectangle are outside the area where
the input bitmap was placed, then they will be transparent black in output.

Return output.

The width attribute must return the ImageBitmap object’s
width, in CSS pixels.

The height attribute must return the ImageBitmap object’s
height, in CSS pixels.

7.9. Animation Frames

Each Document associated with a top-level browsing context has a list of animation frame callbacks, which must be initially empty,
and an animation frame callback identifier, which is a number which must
initially be zero.

When the requestAnimationFrame() method is called, the user agent must run the following steps: