← 5.6 Offline Web applicationsTable of contents7 User interaction →

6 Web application APIs

6.1 Scripting

Status: Last call for comments

6.1.1 Introduction

Status: Last call for comments

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:

6.1.2 Enabling and disabling scripting

Status: Last call for comments

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

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


Scripting is enabled for a node if the Document object of the node (the node itself, if it is itself a Document object) has an associated browsing context, and scripting is enabled in that browsing context.

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

6.1.3 Processing model

Status: Last call for comments

6.1.3.1 Definitions

Status: Last call for comments

A script has:

A script execution environment

The characteristics of the script execution environment depend on the language, and are not defined by this specification.

In JavaScript, the script execution environment consists of the interpreter, the stack of execution contexts, the global code and function code and the Function objects resulting, and so forth.

A list of code entry-points

Each code entry-point represents a block of executable code that the script exposes to other scripts and to the user agent.

Each Function object in a JavaScript script execution environment has a corresponding code entry-point, for instance.

The main program code of the script, if any, is the initial code entry-point. Typically, the code corresponding to this entry-point is executed immediately after the script is parsed.

In JavaScript, this corresponds to the execution context of the global code.

A relationship with the script's global object

An object that provides the APIs that the code can use.

This is typically a Window object. In JavaScript, this corresponds to the global object.

When a script's global object is an empty object, it can't do anything that interacts with the environment.

If the script's global object is a Window object, then in JavaScript, the ThisBinding of the global execution context for this script must be the Window object's WindowProxy object, rather than the global object. [ECMA262]

This is a willful violation of the JavaScript specification current at the time of writing (ECMAScript edition 5, as defined in section 10.4.1.1 Initial Global Execution Context, step 3). The JavaScript specification requires that the this keyword in the global scope return the global object, but this is not compatible with the security design prevalent in implementations as specified herein. [ECMA262]

A relationship with the script's browsing context

A browsing context that is assigned responsibility for actions taken by the script.

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

A relationship with the script's document

A Document that is assigned responsibility for actions taken by the script.

When a script fetches a resource, the current address of the script's document will be used to set the Referer (sic) header.

A URL character encoding

A character encoding, set when the script is created, used to encode URLs. If the character encoding is set from another source, e.g. a document's character encoding, then the script's URL character encoding must follow the source, so that if the source's changes, so does the script's.

A base URL

A URL, set when the script is created, used to resolve relative URLs. If the base URL is set from another source, e.g. a document base URL, then the script's base URL must follow the source, so that if the source's changes, so does the script's.

6.1.3.2 Calling scripts

Status: Last call for comments

When a user agent is to jump to a code entry-point for a script, for example to invoke an event listener defined in that script, the user agent must run the following steps:

  1. If the script's global object is a Window object whose Document object is not fully active, then abort these steps without doing anything. The callback is not fired.

  2. Set the entry script to be the script being invoked.

  3. Make the script execution environment for the script execute the code for the given code entry-point.

  4. Set the entry script back to whatever it was when this algorithm started.

This algorithm is not invoked by one script calling another.

6.1.3.3 Creating scripts

Status: Last call for comments

When the specification says that a script is to be created, given some script source, its scripting language, a global object, a browsing context, a URL character encoding, and a base URL, the user agent must run the following steps:

  1. If scripting is disabled for browsing context passed to this algorithm, then abort these steps, as if the script did nothing but return void.

  2. Set up a script execution environment as appropriate for the scripting language.

  3. Parse/compile/initialize the source of the script using the script execution environment, as appropriate for the scripting language, and thus obtain the list of code entry-points for the script. If the semantics of the scripting language and the given source code are such that there is executable code to be immediately run, then the initial code entry-point is the entry-point for that code.

  4. Set up the script's global object, the script's browsing context, the script's document, the script's URL character encoding, and the script's base URL from the settings passed to this algorithm.

  5. Jump to the script's initial code entry-point.


When the user agent is to create an impotent script, given some script source, its scripting language, and a browsing context, the user agent must create a script, using the given script source and scripting language, using a new empty object as the global object, and using the given browsing context as the browsing context. The URL character encoding and base URL for the resulting script are not important as no APIs are exposed to the script.


When the specification says that a script is to be created from a node node, given some script source and its scripting language, the user agent must create a script, using the given script source and scripting language, and using the script settings determined from the node node.

The script settings determined from the node node are computed as follows:

  1. Let document be the Document of node (or node itself if it is a Document).

  2. The browsing context is the browsing context of document.

  3. The global object is the Window object of document.

  4. The URL character encoding is the character encoding of document. (This is a reference, not a copy.)

  5. The base URL is the base URL of document. (This is a reference, not a copy.)

6.1.3.4 Killing scripts

Status: Last call for comments

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

6.1.4 Event loops

Status: Last call for comments

6.1.4.1 Definitions

Status: Last call for comments

To coordinate events, user interaction, scripts, rendering, networking, and so forth, user agents must use event loops as described in this section.

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

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

Other specifications can define new kinds of event loops that aren't associated with browsing contexts; in particular, the Web Workers specification does so.

An event loop has one or more task queues. A task queue is an ordered list of tasks, which can be:

Events

Asynchronously dispatching an Event object at a particular EventTarget object is a task.

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

Parsing

The HTML parser tokenizing a single byte, and then processing any resulting tokens, is a task.

Callbacks

Calling a callback asynchronously is a task.

Using a resource

When an algorithm fetches a resource, if the fetching occurs asynchronously then the processing of the resource once some or all of the resource is available is a task.

Reacting to DOM manipulation

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

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. All the tasks from one particular task source (e.g. the callbacks generated by timers, the events dispatched for mouse movements, the tasks queued for the parser) 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 task that is queued onto a task queue of an event loop defined by this specification is associated with a Document; if the task was queued in the context of an element, then it is the element's Document; if the task was queued in the context of a browsing context, then it is the browsing context's active document at the time the task was queued; if the task was queued by or for a script then the document is the script's document.

A user agent is required to have one storage mutex. This mutex is used to control access to shared state like cookies. At any one point, the storage mutex is either free, or owned by a particular event loop or instance of the fetching algorithm.

Whenever a script calls into a plugin, and whenever a plugin calls into a script, the user agent must release the storage mutex.

6.1.4.2 Processing model

Status: Last call for comments

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

  1. Run the oldest task on one of the event loop's task queues, ignoring tasks whose associated Documents are not fully active. The user agent may pick any task queue.

  2. If the storage mutex is now owned by the event loop, release it so that it is once again free.

  3. Remove that task from its task queue.

  4. If any asynchronously-running algorithms are awaiting a stable state, then run their synchronous section and then resume running their asynchronous algorithm.

    A synchronous section never mutates the DOM, runs any script, or has any other side-effects.

    Steps in synchronous sections are marked with ⌛.

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

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


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

  1. Let task source be the task source of the currently running task.

  2. Stop the currently running task, allowing the event loop to resume, but continue these steps asynchronously.

  3. Wait until the condition goal is met.

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

  5. Return to the caller.


Some of the algorithms in this specification, for historical reasons, require the user agent to pause while running a task until some condition has been 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.


When a user agent is to obtain the storage mutex as part of running a task, it must run through the following steps:

  1. If the storage mutex is already owned by this task's event loop, then abort these steps.

  2. Otherwise, pause until the storage mutex can be taken by the event loop.

  3. Take ownership of the storage mutex.

6.1.4.3 Generic task sources

Status: Last call for comments

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

The DOM manipulation task source

This task source is used for features that react to DOM manipulations, such as things that happen asynchronously when an element is inserted into the document.

The user interaction task source

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

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

The networking task source

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

The history traversal task source

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

6.1.5 The javascript: protocol

Status: Last call for comments

When a URL using the javascript: protocol is dereferenced, the user agent must run the following steps:

  1. Let the script source be the string obtained using the content retrieval operation defined for javascript: URLs. [JSURL]

  2. Use the appropriate step from the following list:

    If a browsing context is being navigated to a javascript: URL, and the active document of that browsing context has the same origin as the script given by that URL

    Let address be the address of the active document of the browsing context being navigated.

    If address is about:blank, and the browsing context being navigated has a creator browsing context, then let address be the address of the creator Document instead.

    Create a script from the Document node of the active document, using the aforementioned script source, and assuming the scripting language is JavaScript.

    Let result be the return value of the initial code entry-point of this script. If an exception was raised, let result be void instead. (The result will be void also if scripting is disabled.)

    When it comes time to set the document's address in the navigation algorithm, use address as the override URL.

    If the Document object of the element, attribute, or style sheet from which the javascript: URL was reached has an associated browsing context

    Create an impotent script using the aforementioned script source, with the scripting language set to JavaScript, and with the Document's object's browsing context as the browsing context.

    Let result be the return value of the initial code entry-point of this script. If an exception was raised, let result be void instead. (The result will be void also if scripting is disabled.)

    Otherwise

    Let result be void.

  3. If the result of executing the script is void (there is no return value), then the URL must be treated in a manner equivalent to an HTTP resource with an HTTP 204 No Content response.

    Otherwise, the URL must be treated in a manner equivalent to an HTTP resource with a 200 OK response whose Content-Type metadata is text/html and whose response body is the return value converted to a string value.

    Certain contexts, in particular img elements, ignore the Content-Type metadata.

So for example a javascript: URL for a src attribute of an img element would be evaluated in the context of an empty object as soon as the attribute is set; it would then be sniffed to determine the image type and decoded as an image.

A javascript: URL in an href attribute of an a element would only be evaluated when the link was followed.

The src attribute of an iframe element would be evaluated in the context of the iframe's own browsing context; once evaluated, its return value (if it was not void) would replace that browsing context's document, thus changing the variables visible in that browsing context.

6.1.6 Events

Status: Last call for comments

6.1.6.1 Event handlers

Status: Last call for comments

Many objects can have event handlers specified. These act as bubbling event listeners for the object on which they are specified.

An event handler can either have the value null or be set to a Function object. Initially, event handlers must be set to null.

Event handlers are exposed in one or two ways.

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

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


Event handler IDL attributes, on setting, must set the corresponding event handler to their new value, and on getting, must return whatever the current value of the corresponding event handler is (possibly null).

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

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

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


Event handler content attributes, when specified, must contain valid JavaScript code matching the FunctionBody production. [ECMA262]

When an event handler content attribute is set, if the element is owned by a Document that is in a browsing context, and scripting is enabled for that browsing context, the user agent must run the following steps to create a script after setting the content attribute to its new value:

  1. Set up a script execution environment for JavaScript.

  2. Using this script execution environment, create a function object (as defined in ECMAScript edition 5 section 13.2 Creating Function Objects), with:

    Parameter list FormalParameterList
    If the attribute is the onerror attribute of the Window object
    Let the function have three arguments, named event, source, and fileno.
    Otherwise
    Let the function have a single argument called event.
    Function body FunctionBody
    The event handler content attribute's new value.
    Lexical Environment Scope
    1. Let Scope be the result of NewObjectEnvironment(the element's Document, the global environment).
    2. If the element has a form owner, let Scope be the result of NewObjectEnvironment(the element's form owner, Scope).
    3. Let Scope be the result of NewObjectEnvironment(the element's object, Scope).

    NewObjectEnvironment() is defined in ECMAScript edition 5 section 10.2.2.3 NewObjectEnvironment (O, E). [ECMA262]

    Boolean flag Strict
    False.

    Let this new function be the only entry in the script's list of code entry-points.

  3. If the previous steps failed to compile the script, then set the corresponding event handler to null and abort these steps.

  4. Set up the script's global object, the script's browsing context, the script's document, the script's URL character encoding, and the script's base URL from the script settings determined from the node on which the attribute is being set.

  5. Set the corresponding event handler to the aforementioned function.

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

When an event handler content attribute is set on an element owned by a Document that is not in a browsing context, the corresponding event handler is not changed.


All event handlers on an object, whether an element or some other object, and whether set to null or to a Function object, must be registered as event listeners on the object when it is created, as if the addEventListener() method on the object's EventTarget interface had been invoked, with the event type (type argument) equal to the type corresponding to the event handler (the event handler event type), the listener set to be a target and bubbling phase listener (useCapture argument set to false), and the event listener itself (listener argument) set to do nothing while the event handler's value is not a Function object, and set to invoke the call() callback of the Function object associated with the event handler otherwise.

Event handlers therefore always fire before event listeners attached using addEventListener().

The listener argument is emphatically not the event handler itself.

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

When an event handler's Function object is invoked, its call() callback must be invoked with one argument, set to the Event object of the event in question.

The handler's return value must then be processed as follows:

If the event type is mouseover

If the return value is a boolean with the value true, then the event must be canceled.

If the event object is a BeforeUnloadEvent object

If the return value is a string, and the event object's returnValue attribute's value is the empty string, then set the returnValue attribute's value to the return value.

Otherwise

If the return value is a boolean with the value false, then the event must be canceled.


The Function interface represents a function in the scripting language being used. It is represented in IDL as follows:

[Callback=FunctionOnly, NoInterfaceObject]
interface Function {
  any call(in any... arguments);
};

The call(...) method is the object's callback.

In JavaScript, any Function object implements this interface.

If the Function object is a JavaScript Function, then when it is invoked by the user agent, the user agent must set the thisArg (as defined by ECMAScript edition 5 section 10.4.3 Entering Function Code) to the event handler's object. [ECMA262]

For example, the following document fragment:

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

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

The return value of the function is 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 the message to show the user.

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

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

Event handler Event handler event type
onabort abort
oncanplay canplay
oncanplaythrough canplaythrough
onchange change
onclick click
oncontextmenu contextmenu
ondblclick dblclick
ondrag drag
ondragend dragend
ondragenter dragenter
ondragleave dragleave
ondragover dragover
ondragstart dragstart
ondrop drop
ondurationchange durationchange
onemptied emptied
onended ended
onformchange formchange
onforminput forminput
oninput input
oninvalid invalid
onkeydown keydown
onkeypress keypress
onkeyup keyup
onloadeddata loadeddata
onloadedmetadata loadedmetadata
onloadstart loadstart
onmousedown mousedown
onmousemove mousemove
onmouseout mouseout
onmouseover mouseover
onmouseup mouseup
onmousewheel mousewheel
onpause pause
onplay play
onplaying playing
onprogress progress
onratechange ratechange
onreadystatechange readystatechange
onscroll scroll
onseeked seeked
onseeking seeking
onselect select
onshow show
onstalled stalled
onsubmit submit
onsuspend suspend
ontimeupdate timeupdate
onvolumechange volumechange
onwaiting waiting

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

Event handler Event handler event type
onblur blur
onerror error
onfocus focus
onload load

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

Event handler Event handler event type
onafterprint afterprint
onbeforeprint beforeprint
onbeforeunload beforeunload
onblur blur
onerror error
onfocus focus
onhashchange hashchange
onload load
onmessage message
onoffline offline
ononline online
onpagehide pagehide
onpageshow pageshow
onpopstate popstate
onredo redo
onresize resize
onstorage storage
onundo undo
onunload unload

The onerror handler is also used for reporting script errors.

6.1.6.3 Event firing

Status: Last call for comments

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

Firing a click event means that a click event, which bubbles and is cancelable, and which uses the MouseEvent interface, must be dispatched at the given target. The event object must have its screenX, screenY, clientX, clientY, and button attributes set to 0, its ctrlKey, shiftKey, altKey, and metaKey attributes set according to the current state of the key input device, if any (false for any keys that are not available), its detail attribute set to 1, and its relatedTarget attribute set to 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.

Firing a simple event named e means that an 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 dispatched at the given target.

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

6.1.6.4 Events and the Window object

Status: Last call for comments

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 also dispatch the event to the Window, as follows:

  1. In the capture phase, the event must propagate to the Window object before propagating to any of the nodes, as if the Window object was the parent of the Document in the dispatch chain.
  2. In the bubble phase, the event must propagate up to the Window object at the end of the phase, unless bubbling has been prevented, again as if the Window object was the parent of the Document in the dispatch chain.
6.1.6.5 Runtime script errors

Status: Last call for comments

This section only applies to user agents that support scripting in general and JavaScript in particular.

Whenever an uncaught runtime script error occurs in one of the scripts associated with a Document, the user agent must report the error using the onerror event handler of the script's global object. If the error is still not handled after this, then the error may be reported to the user.


When the user agent is required to report an error error using the event handler onerror, it must run these steps, after which the error is either handled or not handled:

If the value of onerror is a Function

The function must be invoked with three arguments. The three arguments passed to the function are all DOMStrings; the first must give the message that the UA is considering reporting, the second must give the absolute URL of the resource in which the error occurred, and the third must give the line number in that resource on which the error occurred.

If the function returns false, then the error is handled. Otherwise, the error is not handled.

Any uncaught exceptions thrown or errors caused by this function may be reported to the user immediately after the error that the function was called for; the report an error algorithm must not be used to handle exceptions thrown or errors caused by this function.

Otherwise

The error is not handled.

6.2 Timers

Status: Last call for comments

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

[Supplemental, NoInterfaceObject]
interface WindowTimers {
  long setTimeout(in any handler, in optional any timeout, in any... args);
  void clearTimeout(in long handle);
  long setInterval(in any handler, in optional any timeout, in any... args);
  void clearInterval(in long handle);
};
Window implements WindowTimers;
handle = window . setTimeout( handler [, timeout [, arguments ] ] )

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

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

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

window . clearTimeout( handle )

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

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

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() identified by handle.

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

The WindowTimers interface adds to the Window interface and the WorkerUtils interface (part of Web Workers).

Each object that implements the WindowTimers interface has a list of active timeouts and a list of active intervals. Each entry in these lists is identified by a number, which must be unique within its list for the lifetime of the object that implements the WindowTimers interface.


The setTimeout() method must run the following steps:

  1. Let handle be a user-agent-defined integer that is greater than zero that will identify the timeout to be set by this call.

  2. Add an entry to the list of active timeouts for handle.

  3. Get the timed task handle in the list of active timeouts, and let task be the result.

  4. Get the timeout, and let timeout be the result.

  5. If the currently running task is a task that was created by the setTimeout() method, and timeout is less than 4, then increase timeout to 4.

  6. Return handle, and then continue running this algorithm asynchronously.

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

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

    Otherwise, act as described in the specification that defines that the WindowTimers interface is implemented by some other object.

  8. Wait until any invocations of this algorithm started before this one whose timeout is equal to or less than this one's have completed.

  9. Queue the task task.

The clearTimeout() method must clear the entry identified as handle from the list of active timeouts of the WindowTimers object on which the method was invoked, where handle is the argument passed to the method.


The setInterval() method must run the following steps:

  1. Let handle be a user-agent-defined integer that is greater than zero that will identify the interval to be set by this call.

  2. Add an entry to the list of active intervals for handle.

  3. Get the timed task handle in the list of active intervals, and let task be the result.

  4. Get the timeout, and let timeout be the result.

  5. If timeout is less than 10, then increase timeout to 10.

  6. Return handle, and then continue running this algorithm asynchronously.

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

    Otherwise, if the method context is a WorkerUtils object, wait until interval milliseconds have passed with the worker not suspended (not necessarily consecutively).

    Otherwise, act as described in the specification that defines that the WindowTimers interface is implemented by some other object.

  8. Queue the task task.

  9. Return to the step labeled wait.

The clearInterval() method must clear the entry identified as handle from the list of active intervals of the WindowTimers object on which the method was invoked, where handle is the argument passed to the method.


The method context, when referenced by the algorithms in this section, is the object on which the method for which the algorithm is running is implemented (a Window or WorkerUtils object).

When the above methods are invoked and try to get the timed task handle in list list, they must run the following steps:

  1. If the first argument to the invoked method is an object that has an internal [[Call]] method, then return a task that checks if the entry for handle in list has been cleared, and if it has not, calls the aforementioned [[Call]] method with as its arguments the third and subsequent arguments to the invoked method (if any), and abort these steps.

    Otherwise, continue with the remaining steps.

  2. Apply the ToString() abstract operation to the first argument to the method, and let script source be the result. [ECMA262]

  3. Let script language be JavaScript.

  4. If the method context is a Window object, let global object be the method context, let browsing context be the browsing context with which global object is associated, let character encoding be the character encoding of the Document associated with global object (this is a reference, not a copy), and let base URL be the base URL of the Document associated with global object (this is a reference, not a copy).

    Otherwise, if the method context is a WorkerUtils object, let global object, browsing context, document, character encoding, and base URL be the script's global object, script's browsing context, script's document, script's URL character encoding, and script's base URL (respectively) of the script that the run a worker algorithm created when it created the method context.

    Otherwise, act as described in the specification that defines that the WindowTimers interface is implemented by some other object.

  5. Return a task that checks if the entry for handle in list has been cleared, and if it has not, creates a script using script source as the script source, scripting language as the scripting language, global object as the global object, browsing context as the browsing context, document as the document, character encoding as the URL character encoding, and base URL as the base URL.

When the above methods are to get the timeout, they must run the following steps:

  1. Let timeout be the second argument to the method, or zero if the argument was omitted.

  2. Apply the ToString() abstract operation to timeout, and let timeout be the result. [ECMA262]

  3. Apply the ToNumber() abstract operation to timeout, and let timeout be the result. [ECMA262]

  4. If timeout is an Infinity value, a Not-a-Number (NaN) value, or negative, let timeout be zero.

  5. Round timeout down to the nearest integer, and let timeout be the result.

  6. Return timeout.


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

6.3 User prompts

Status: Last call for comments

6.3.1 Simple dialogs

Status: Last call for comments

window . alert(message)

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

A call to the navigator.yieldForStorageUpdates() method is implied when this method is invoked.

result = window . confirm(message)

Displays a modal OK/Cancel prompt with the given message, waits for the user to dismiss it, and returns true if the user clicks OK and false if the user clicks Cancel.

A call to the navigator.yieldForStorageUpdates() method is implied when this method is invoked.

result = window . prompt(message [, default] )

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.

A call to the navigator.yieldForStorageUpdates() method is implied when this method is invoked.

The alert(message) method, when invoked, must release the storage mutex and show the given message to the user. The user agent may make the method wait for the user to acknowledge the message before returning; if so, the user agent must pause while the method is waiting.

The confirm(message) method, when invoked, must release the storage mutex and show the given message to the user, and ask the user to respond with a positive or negative response. The user agent must then pause as the method waits for the user's response. If the user responds positively, the method must return true, and if the user responds negatively, the method must return false.

The prompt(message, default) method, when invoked, must release the storage mutex, show the given message to the user, and ask the user to either respond with a string value or abort. The user agent must then pause as the method waits for the user's response. The second argument is optional. If the second argument (default) is present, then the response must be defaulted to the value given by default. If the user aborts, then the method must return null; otherwise, the method must return the string that the user responded with.

6.3.2 Printing

Status: Last call for comments

window . print()

Prompts the user to print the page.

A call to the navigator.yieldForStorageUpdates() method is implied when this method is invoked.

The print() method, when invoked, must run the printing 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:

  1. The user agent may display a message to the user and/or may abort these steps.

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

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

  2. The user agent must fire a simple event named beforeprint at the Window object of the Document that is being printed, as well as any nested browsing contexts in it.

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

  3. The user agent must release the storage mutex.

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

  5. The user agent must fire a simple event named afterprint at the Window object of the Document that is being printed, as well as any nested browsing contexts in it.

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

6.3.3 Dialogs implemented using separate documents

Status: Last call for comments

result = window . showModalDialog(url [, argument] )

Prompts the user with the given page, waits for that page to close, and returns the return value.

A call to the navigator.yieldForStorageUpdates() method is implied when this method is invoked.

The showModalDialog(url, argument) method, when invoked, must cause the user agent to run the following steps:

  1. Resolve url relative to the entry script's base URL.

    If this fails, then throw a SYNTAX_ERR exception and abort these steps.

  2. Release the storage mutex.

  3. If the user agent is configured such that this invocation of showModalDialog() is somehow disabled, then return the empty string and abort these steps.

    User agents are expected to disable this method in certain cases to avoid user annoyance (e.g. as part of their popup blocker feature). For instance, a user agent could require that a site be white-listed before enabling this method, or the user agent could be configured to only allow one modal dialog at a time.

  4. Let the list of background browsing contexts be a list of all the browsing contexts that:

    ...as well as any browsing contexts that are nested inside any of the browsing contexts matching those conditions.

  5. Disable the user interface for all the browsing contexts in the list of background browsing contexts. This should prevent the user from navigating those browsing contexts, causing events to be sent to those browsing context, or editing any content in those browsing contexts. However, it does not prevent those browsing contexts from receiving events from sources other than the user, from running scripts, from running animations, and so forth.

  6. Create a new auxiliary browsing context, with the opener browsing context being the browsing context of the Window object on which the showModalDialog() method was called. The new auxiliary browsing context has no name.

    This browsing context's Documents' Window objects all implement the WindowModal interface.

  7. Let the dialog arguments of the new browsing context be set to the value of argument, or the 'undefined' value if the argument was omitted.

  8. Let the dialog arguments' origin be the origin of the script that called the showModalDialog() method.

  9. Navigate the new browsing context to the absolute URL that resulted from resolving url earlier, with replacement enabled, and with the browsing context of the script that invoked the method as the source browsing context.

  10. Spin the event loop until the new browsing context is closed. (The user agent must allow the user to indicate that the browsing context is to be closed.)

  11. Reenable the user interface for all the browsing contexts in the list of background browsing contexts.

  12. Return the auxiliary browsing context's return value.

The Window objects of Documents hosted by browsing contexts created by the above algorithm must all have the WindowModal interface added to their Window interface:

[Supplemental, NoInterfaceObject] interface WindowModal {
  readonly attribute any dialogArguments;
           attribute DOMString returnValue;
};
window . dialogArguments

Returns the argument argument that was passed to the showModalDialog() method.

window . returnValue [ = value ]

Returns the current return value for the window.

Can be set, to change the value that will be returned by the showModalDialog() method.

Such browsing contexts have associated dialog arguments, which are stored along with the dialog arguments' origin. These values are set by the showModalDialog() method in the algorithm above, when the browsing context is created, based on the arguments provided to the method.

The dialogArguments IDL attribute, on getting, must check whether its browsing context's active document's origin is the same as the dialog arguments' origin. If it is, then the browsing context's dialog arguments must be returned unchanged. Otherwise, if the dialog arguments are an object, then the empty string must be returned, and if the dialog arguments are not an object, then the stringification of the dialog arguments must be returned.

These browsing contexts also have an associated return value. The return value of a browsing context must be initialized to the empty string when the browsing context is created.

The returnValue IDL attribute, on getting, must return the return value of its browsing context, and on setting, must set the return value to the given new value.

The window.close() method can be used to close the browsing context.

6.4 System state and capabilities

Status: Last call for comments

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

interface Navigator {
  // objects implementing this interface also implement the interfaces given below
};
Navigator implements NavigatorID;
Navigator implements NavigatorOnLine;
Navigator implements NavigatorAbilities;

[Supplemental, NoInterfaceObject]
interface NavigatorID {
  readonly attribute DOMString appName;
  readonly attribute DOMString appVersion;
  readonly attribute DOMString platform;
  readonly attribute DOMString userAgent;
};

[Supplemental, NoInterfaceObject]
interface NavigatorOnLine {
  readonly attribute boolean onLine;
};

[Supplemental, NoInterfaceObject]
interface NavigatorAbilities {
  // content handler registration
  void registerProtocolHandler(in DOMString scheme, in DOMString url, in DOMString title);
  void registerContentHandler(in DOMString mimeType, in DOMString url, in DOMString title);
  void yieldForStorageUpdates();
};

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

6.4.1 Client identification

Status: Last call for comments

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

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

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

window . navigator . appName

Returns the name of the browser.

window . navigator . appVersion

Returns the version of the browser.

window . navigator . platform

Returns the name of the platform.

window . navigator . userAgent

Returns the complete User-Agent header.

appName

Must return either the string "Netscape" or the full name of the browser, e.g. "Mellblom Browsernator".

appVersion

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

platform

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

userAgent

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.

6.4.2 Custom scheme and content handlers

Status: Last call for comments

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 ([RFC5724]), 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/directory files ([RFC2425]), so that if the user has no native application capable of handling vCards ([RFC2426]), his Web browser can instead suggest he use that site to view contact information stored on vCards that he opens.

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 SECURITY_ERR exception if the user agent blocks the registration (this might happen if trying to register as a handler for "http", for instance).

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

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

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

The arguments to the methods have the following meanings and corresponding implementation requirements:

protocol (registerProtocolHandler() only)

A scheme, such as ftp or sms. 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 "ftp:"), will never match anything, since schemes don't contain colons.

This feature is not intended to be used with non-standard protocols.

mimeType (registerContentHandler() only)

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

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

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

url

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

When the user agent uses this URL, it must replace the first occurrence of the exact literal string "%s" with an escaped version of the absolute URL of the content in question (as defined below), then resolve the resulting URL, relative to the base URL of the entry script at the time the registerContentHandler() or registerProtocolHandler() methods were invoked, and then navigate an appropriate browsing context to the resulting URL using the GET method (or equivalent for non-HTTP URLs).

To get the escaped version of the absolute URL of the content in question, the user agent must replace every character in that absolute URL that doesn't match the <query> production defined in RFC 3986 by the percent-encoded form of that character. [RFC3986]

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

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

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

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

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

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

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

title

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

User agents should raise SECURITY_ERR exceptions if the methods are called with scheme or mimeType values that the UA deems to be "privileged". For example, a site attempting to register a handler for http URLs or text/html content in a Web browser would likely cause an exception to be raised.

User agents must raise a SYNTAX_ERR exception if the url argument passed to one of these methods does not contain the exact literal string "%s", or if resolving the url argument with the first occurrence of the string "%s" removed, relative to the entry script's base URL, is not successful.

User agents must not raise any other exceptions (other than binding-specific exceptions, such as for an incorrect number of arguments in an JavaScript implementation).

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

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

6.4.2.1 Security and privacy

Status: Last call for comments

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. It is strongly recommended that user agents do not automatically change any defaults, as this could lead the user to send data to remote hosts that the user is not expecting. New handlers registering themselves should never automatically cause those sites to be used.

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

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

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

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

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

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

Leaking secure URLs. User agents should not send HTTPS URLs to third-party sites registered as content handlers, in the same way that user agents do not send Referer (sic) HTTP headers from secure sites to third-party sites.

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

6.4.2.2 Sample user interface

Status: Last call for comments

This section is non-normative.

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

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

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

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

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

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

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

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

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

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

6.4.3 Manually releasing the storage mutex

Status: Last call for comments

window . navigator . yieldForStorageUpdates()

If a script uses the document.cookie API, or the localStorage API, the browser will block other scripts from accessing cookies or storage until the first script finishes. [WEBSTORAGE]

Calling the navigator.yieldForStorageUpdates() method tells the user agent to unblock any other scripts that may be blocked, even though the script hasn't returned.

Values of cookies and items in the Storage objects of localStorage attributes can change after calling this method, whence its name. [WEBSTORAGE]

The yieldForStorageUpdates() method, when invoked, must, if the storage mutex is owned by the event loop of the task that resulted in the method being called, release the storage mutex so that it is once again free. Otherwise, it must do nothing.