The setTimeout()
and setInterval()
methods allow authors to schedule timer-based callbacks.
[NoInterfaceObject]
interface WindowTimers {
long setTimeout(Function handler, optional long timeout, any... arguments);
long setTimeout(DOMString handler, optional long timeout, any... arguments);
void clearTimeout(long handle);
long setInterval(Function handler, optional long timeout, any... arguments);
long setInterval(DOMString handler, optional long timeout, any... arguments);
void clearInterval(long handle);
};
Window implements WindowTimers;
setTimeout( handler [, timeout [, arguments... ] ] )Schedules a timeout to run handler after timeout milliseconds. Any arguments are passed straight through to the handler.
setTimeout( code [, timeout ] )Schedules a timeout to compile and run code after timeout milliseconds.
clearTimeout( handle )Cancels the timeout set with setTimeout() identified by handle.
setInterval( handler [, timeout [, arguments... ] ] )Schedules a timeout to run handler every timeout milliseconds. Any arguments are passed straight through to the handler.
setInterval( code [, timeout ] )Schedules a timeout to compile and run code every timeout milliseconds.
clearInterval( handle )Cancels the timeout set with setInterval() identified by handle.
This API does not guarantee that timers will run 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 WorkerGlobalScope interface (part of Web Workers).
Each object that implements the WindowTimers interface has 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 run
the following steps:
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.
Add an entry to the list of active timers for handle.
Get the timed task handle in the list of active timers, and let task be the result. This algorithm uses the first argument to the method (handler) and, if there are any, the third and subsequent arguments to the method (arguments), to establish precisely what task does.
Let timeout be the second argument to the method, or zero if the argument was omitted.
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.
Return handle, and then continue running this algorithm asynchronously.
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 WorkerGlobalScope 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.
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 ":
var log = '';
function logger(s) { log += s + ' '; }
setTimeout({ toString: function () {
setTimeout("logger('ONE')", 100);
return "logger('TWO')";
} }, 100);
Optionally, wait a further user-agent defined length of time.
This is intended to allow user agents to pad timeouts as needed to optimise 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, 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).
The setInterval() method must run
the following steps:
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.
Add an entry to the list of active timers for handle.
Get the timed task handle in the list of active timers, and let task be the result. This algorithm uses the first argument to the method (handler) and, if there are any, the third and subsequent arguments to the method (arguments), to establish precisely what task does.
Let timeout be the second argument to the method, or zero if the argument was omitted.
If timeout is less than 4, then increase timeout to 4.
Return handle, and then continue running this algorithm asynchronously.
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 WorkerGlobalScope 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.
Optionally, wait a further user-agent defined length of time.
This is intended to allow user agents to pad timeouts as needed to optimise 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.
Return to the step labeled wait.
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, where handle
is the argument passed to the method, if any. (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.)
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
WorkerGlobalScope object). The method context proxy is the method
context if that is a WorkerGlobalScope object, or else the
WindowProxy that corresponds to the method context.
When the above methods are invoked and try to get the timed task handle in list list, they must run the following steps:
If the first argument to the invoked method is a Function, then return a task that runs the following substeps, and then abort these steps:
If the entry for handle in list has been cleared, then abort this task's substeps.
Call the Function. Use the third and subsequent arguments to the invoked
method (if any) as the arguments for invoking the Function. Use the method
context proxy as the thisArg for invoking the
Function. [ECMA262]
Otherwise, continue with the remaining steps.
Let script source be the first argument to the method.
Let script language be JavaScript.
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
document and referrer source be the
Document associated with global object, 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 WorkerGlobalScope object, let
global object, browsing context, document, referrer source, character
encoding, and base URL be the script's global object,
script's browsing context, script's document, script's referrer
source, 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.
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, the URL where script source can be found, scripting language as the scripting language, global object as the global object, browsing context as the browsing context, document as the document, referrer source as the referrer source, character encoding as the URL character encoding, and base URL as the base URL.
The task source for these tasks is the timer task source.
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.
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.
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 run the following steps:
If the event loop's termination nesting level is non-zero, optionally abort these steps.
Release the storage mutex.
Optionally, abort these steps. (For example, the user agent might give the user the option to ignore all alerts, and would thus abort at this step whenever the method was invoked.)
Show the given message to the user.
Optionally, pause while waiting for the user to acknowledge the message.
The confirm(message) method,
when invoked, must run the following steps:
If the event loop's termination nesting level is non-zero, optionally abort these steps, returning false.
Release the storage mutex.
Optionally, return false and abort these steps. (For example, the user agent might give the user the option to ignore all prompts, and would thus abort at this step whenever the method was invoked.)
Show the given message to the user, and ask the user to respond with a positive or negative response.
Pause until the user responds either positively or negatively.
If the user responded positively, return true; otherwise, the user responded negatively: return false.
The prompt(message, default) method, when invoked, must run the following steps:
If the event loop's termination nesting level is non-zero, optionally abort these steps, returning null.
Release the storage mutex.
Optionally, return null and abort these steps. (For example, the user agent might give the user the option to ignore all prompts, and would thus abort at this step whenever the method was invoked.)
Show the given message to the user, and ask the user to either respond with a string value or abort. The response must be defaulted to the value given by default.
Pause while waiting for the user's response.
If the user aborts, then return null; otherwise, return the string that the user responded with.
print()Prompts the user to print the page.
A call to the navigator.yieldForStorageUpdates()
method is implied when this method is invoked.
When the print() method
is invoked, if the Document is ready for
post-load tasks, then the user agent must synchronously run
the printing steps. Otherwise, the user agent must only
set the print when loaded flag on the
Document.
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 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.
The user agent must release the storage mutex.
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 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.
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:
Resolve url relative to the entry script's base URL.
If this fails, then throw a SyntaxError exception and abort these steps.
If the event loop's termination nesting level is non-zero, optionally abort these steps, returning the empty string.
Release the storage mutex.
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.
If the active sandboxing flag set of the active document of the browsing context of the incumbent script has its sandboxed auxiliary navigation browsing context flag set, then return the empty string and abort these steps.
Let incumbent origin be the effective script origin of the
incumbent script at the time the showModalDialog() method was called.
Let the list of background browsing contexts be a list of all the browsing contexts that:
Window object on which the showModalDialog() method was called, and that...as well as any browsing contexts that are nested inside any of the browsing contexts matching those conditions.
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.
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.
Set all the flags in the new browsing context's popup sandboxing flag set that are set in the active sandboxing flag set of the active document of the browsing context of the incumbent script. The browsing context of the incumbent script must be set as the new browsing context's one permitted sandboxed navigator.
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.
Let the dialog arguments' origin be incumbent origin.
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 incumbent script as the source browsing context.
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.
Reenable the user interface for all the browsing contexts in the list of background browsing contexts.
If the effective script origin of the auxiliary browsing context's active document at the time the browsing context was closed was the same origin as the dialog arguments' origin, then let return value be the auxiliary browsing context's return value as it stood when the browsing context was closed.
Otherwise, let return value be undefined.
Return return value.
The Window objects of Documents hosted by browsing contexts created by the above algorithm must also implement the
WindowModal interface.
When this happens, the members of the WindowModal interface, in
JavaScript environments, appear to actually be part of the Window interface (e.g.
they are on the same prototype chain as the window.alert()
method).
[NoInterfaceObject] interface WindowModal {
readonly attribute any dialogArguments;
attribute any returnValue;
};
dialogArgumentsReturns the argument argument that was passed to the showModalDialog() method.
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, the IDL attribute must return undefined.
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.
Navigator objectThe 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 NavigatorLanguage;
Navigator implements NavigatorOnLine;
Navigator implements NavigatorContentUtils;
Navigator implements NavigatorStorageUtils;
These interfaces are defined separately so that other specifications can re-use parts of the
Navigator interface.
[NoInterfaceObject]
interface NavigatorID {
readonly attribute DOMString appName;
readonly attribute DOMString appVersion;
readonly attribute DOMString platform;
readonly attribute DOMString userAgent;
const DOMString product = "Gecko"; // for historical reasons
};
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.
navigator . appNameReturns the name of the browser.
navigator . appVersionReturns the version of the browser.
navigator . platformReturns the name of the platform.
navigator . userAgentReturns the complete User-Agent header.
appNameMust return either the string "Netscape" or the full name of the browser, e.g. "Mellblom Browsernator".
appVersionMust 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".
platformMust 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".
userAgentMust 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.
[NoInterfaceObject]
interface NavigatorLanguage {
readonly attribute DOMString? language;
};
navigator . languageReturns a language tag representing the user's preferred language.
languageMust return either the string "en" or a language tag representing the user's preferred language.
As for the API in the previous section, any information in this API that varies
from user to user can be used to profile or identify the user. For this reason, user agent
implementors are encouraged to return null unless the user has explicitly indicated that the site
in question is allowed access to the information.
[NoInterfaceObject]
interface NavigatorContentUtils {
// content handler registration
void registerProtocolHandler(DOMString scheme, DOMString url, DOMString title);
void registerContentHandler(DOMString mimeType, DOMString url, DOMString title);
DOMString isProtocolHandlerRegistered(DOMString scheme, DOMString url);
DOMString isContentHandlerRegistered(DOMString mimeType, DOMString url);
void unregisterProtocolHandler(DOMString scheme, DOMString url);
void unregisterContentHandler(DOMString mimeType, DOMString url);
};
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
navigator . registerProtocolHandler(scheme, url, title)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 exception if the user agent blocks the registration (this
might happen if trying to register as a handler for "http", for instance).
Throws a SyntaxError exception 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. 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.)
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 whitelisted 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 SecurityError
exception.
The following schemes are the whitelisted schemes:
bitcoinircgeomailtomagnetmmsnewsnntpsipsmssmstosshtelurnwebcalxmppThis 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.
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.
If the registerContentHandler()
method is invoked with a MIME type that is in the type blacklist or
that the user agent has deemed a privileged type, the user agent must throw a
SecurityError exception.
The following MIME types are in the type blacklist:
application/x-www-form-urlencodedapplication/xhtml+xmlapplication/xmlimage/gifimage/jpegimage/pngimage/svg+xmlmultipart/x-mixed-replacetext/cache-manifesttext/csstext/htmltext/pingtext/plaintext/xmlapplication/rss+xml and application/atom+xmlThis list can be changed. If there are MIME types that should be added, please send feedback.
A string used to build the URL of the page that will handle the requests.
User agents must throw a SyntaxError exception if the url
argument passed to one of these methods does not contain the exact literal string
"%s".
User agents must throw a SyntaxError exception if resolving the url argument relative to the entry
script's base URL, is not successful.
The resulting absolute URL would by definition not be a valid
URL as it would include the string "%s" which is not a valid
component in a URL.
User agents must throw a SecurityError exception if the resulting absolute
URL has an origin that differs from the origin of the
entry script.
This is forcibly the case if the %s placeholder is in the
scheme, host, or port parts of the URL.
The resulting absolute URL 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 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 is not a character in the URL default encode set with the result of UTF-8 percent encoding that character.
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).
A descriptive title of the handler, which the UA 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 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.
In addition to the registration methods, there are also methods for determining if particular handlers have been registered, and for unregistering handlers.
navigator . isProtocolHandlerRegistered(scheme, url)navigator . isContentHandlerRegistered(mimeType, url)Returns one of the following strings describing the state of the handler given by the arguments:
new
registered
declined
navigator . unregisterProtocolHandler(scheme, url)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
registered
declined
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.
Resolve the string relative to the base URL of the entry script.
If this fails, then throw a SyntaxError exception, aborting the
method.
If the resulting absolute URL's origin is not the same
origin as that of the entry script, throw a SecurityError
exception, aborting the method.
Return the resulting absolute URL as the result of preprocessing the argument.
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:
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 without the user's informed consent, for the same reason that
user agents sometimes avoid sending 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).
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.
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,
"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:

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.
[NoInterfaceObject]
interface NavigatorStorageUtils {
void yieldForStorageUpdates();
};
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.
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.
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.
External interfaceThe external attribute of the Window
interface must return an instance of the External interface. The same object must be
returned each time.
interface External {
void AddSearchProvider(DOMString engineURL);
unsigned long IsSearchProviderInstalled(DOMString engineURL);
};
external . AddSearchProvider( url )Adds the search engine described by the OpenSearch description document at url. [OPENSEARCH]
The OpenSearch description document has to be on the same server as the script that calls this method.
external . IsSearchProviderInstalled( url )Returns a value based on comparing url to the URLs of the results pages of the installed search engines.
The url is compared to the URLs of the results pages of the installed search engines using a prefix match. Only results pages on the same domain as the script that calls this method are checked.
Another way of exposing search engines using
OpenSearch description documents is using a link
element with the search link
type.
The AddSearchProvider()
method, when invoked, must run the following steps:
Optionally, abort these steps. User agents may implement the method as a stub method that never does anything, or may arbitrarily ignore invocations with particular arguments for security, privacy, or usability reasons.
Resolve the value of the method's first argument relative to the entry script's base URL.
If this fails, abort these steps.
Process the resulting absolute URL as the URL to an OpenSearch description document. [OPENSEARCH]
The IsSearchProviderInstalled()
method, when invoked, must run the following steps:
Optionally, return 0 and abort these steps. User agents may implement the method as a stub method that never returns a non-zero value, or may arbitrarily ignore invocations with particular arguments for security, privacy, or usability reasons.
If the origin of the entry script is an opaque identifier (i.e. it has no host component), then return 0 and abort these steps.
Let host1 be the host component of the origin of the entry script.
Resolve the scriptURL argument relative to the entry script's base URL.
If this fails, return 0 and abort these steps.
Let host2 be the host component of the resulting parsed URL.
If the longest suffix in the Public Suffix List that matches the end of host1 is different than the longest suffix in the Public Suffix List that matches the end of host2, then return 0 and abort these steps. [PSL]
If the next domain component of host1 and host2 after their common suffix are not the same, then return 0 and abort these steps.
Let search engines be the list of
search engines known by the user agent and made available to the
user by the user agent for which the resulting absolute
URL is a prefix match of the search engine's
URL, if any. For search engines registered using
OpenSearch description documents, the URL of the
search engine corresponds to the URL given in a Url element whose rel
attribute is "results" (the default). [OPENSEARCH]
If search engines is empty, return 0 and abort these steps.
If the user's default search engine (as determined by the user agent) is one of the search engines in search engines, then return 2 and abort these steps.
Return 1.
interface ImageBitmap {
// opaque object
};
callback ImageBitmapCallback = void (ImageBitmap image);
typedef (HTMLImageElement or
HTMLVideoElement or
HTMLCanvasElement or
Blob or
ImageData or
CanvasRenderingContext2D or
ImageBitmap) ImageBitmapSource;
[NoInterfaceObject]
interface ImageBitmapFactories {
void createImageBitmap(ImageBitmapSource image, ImageBitmapCallback _callback, optional long sx, long sy, long sw, long sh);
};
Window implements ImageBitmapFactories;
WorkerGlobalScope implements ImageBitmapFactories;
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.
createImageBitmap(image, callback [, 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 asynchronously calls callback with a
new ImageBitmap as its argument when it has created one.
If no ImageBitmap object can be constructed, for example because the provided
image data is not actually an image, then the callback
is invoked with null as the value 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.
Throws 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). Throws a SecurityError exception 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 can be obtained from a variety of different objects, using
the createImageBitmap() method. This method
takes two arguments, image and callback. When invoked, the
method must act as follows:
img element
If either the sw or sh arguments are specified
but zero, throw an IndexSizeError exception and abort these steps.
If the img element is not completely
available, then throw an InvalidStateError exception and abort these
steps.
If the origin of the img element's image is not the same
origin as the entry script's origin, then throw a
SecurityError exception and abort these steps.
If the img element's media data is not a bitmap (e.g. it's a vector
graphic), then throw 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.
Return, but continue running these steps asynchronously.
Queue a task to invoke callback with the new
ImageBitmap object as its argument.
video element
If either the sw or sh arguments are specified
but zero, throw an IndexSizeError exception and abort these steps.
If the video element's networkState attribute is NETWORK_EMPTY, then throw an
InvalidStateError exception and abort these steps.
If the origin of the video element is not the same
origin as the entry script's origin, then throw a
SecurityError exception and abort these steps.
If the video element's readyState
attribute is either HAVE_NOTHING or HAVE_METADATA, then throw an
InvalidStateError exception and abort these steps.
Create a new ImageBitmap object.
Let the ImageBitmap object's bitmap data be a copy of the frame at the
current playback position, at the media resource's intrinsic width and intrinsic height (i.e. after any aspect-ratio
correction has been applied), cropped to the source rectangle.
Return, but continue running these steps asynchronously.
Queue a task to invoke callback with the new
ImageBitmap object as its argument.
canvas element
If either the sw or sh arguments are specified
but zero, throw an IndexSizeError exception and abort these steps.
If the canvas element's bitmap data does not have its origin-clean flag set, then throw an
InvalidStateError exception and abort these steps.
If the canvas element's bitmap has either a horizontal dimension or a
vertical dimension equal to zero, then throw an InvalidStateError exception and
abort these steps.
Create a new ImageBitmap object.
Let the ImageBitmap object's bitmap data be a copy of the
canvas element's bitmap data, cropped to the source
rectangle.
Return, but continue running these steps asynchronously.
Queue a task to invoke callback with the new
ImageBitmap object as its argument.
Blob object
If either the sw or sh arguments are specified
but zero, throw an IndexSizeError exception and abort these steps.
If the Blob object has been neutered through the close method, then throw an InvalidStateError
exception and abort these steps.
Return, but continue running these steps asynchronously.
Read the Blob object's data. If an error
occurs during reading of the object, then queue a task to invoke callback with null as the argument, and abort these steps.
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, queue a task to invoke callback with null as the argument, 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.
Queue a task to invoke callback with the new
ImageBitmap object as its argument.
ImageData object
If either the sw or sh arguments are specified
but zero, throw an IndexSizeError exception and abort these steps.
Create a new ImageBitmap object.
Let the ImageBitmap object's bitmap data be the image data given by the
ImageData object, cropped to the source rectangle, using the value
of the object's resolution attribute as the
object's pixel density.
Return, but continue running these steps asynchronously.
Queue a task to invoke callback with the new
ImageBitmap object as its argument.
CanvasRenderingContext2D object
If either the sw or sh arguments are specified
but zero, throw an IndexSizeError exception and abort these steps.
If the CanvasRenderingContext2D object's scratch bitmap does
not have its origin-clean flag set, then throw
an InvalidStateError 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 throw an
InvalidStateError exception and abort these steps.
Create a new ImageBitmap object.
Let the ImageBitmap object's bitmap data be a copy of the
CanvasRenderingContext2D object's scratch bitmap, cropped to
the source rectangle.
Return, but continue running these steps asynchronously.
Queue a task to invoke callback with the new
ImageBitmap object as its argument.
ImageBitmap object
If either the sw or sh arguments are specified
but zero, throw an IndexSizeError exception and abort these steps.
Create a new ImageBitmap object.
Let the ImageBitmap object's bitmap data be a copy of the image argument's bitmap data, cropped to the source
rectangle.
Return, but continue running these steps asynchronously.
Queue a task to invoke callback with the new
ImageBitmap object as its argument.
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.
Let output's pixel density be input's pixel density.
Return output.
Using this API, a sprite sheet can be precut and prepared:
var sprites = {};
function loadMySprites(loadedCallback) {
var pending = 0;
function getSpriteAdder(name) {
pending += 1;
return function (image) {
sprites[name] = image;
pending -= 1;
if (!pending)
loadedCallback();
};
}
var image = new Image();
image.src = 'mysprites.png';
image.onload = function () {
createImageBitmap(image, getSpriteAdder('woman'), 0, 0, 40, 40);
createImageBitmap(image, getSpriteAdder('man'), 40, 0, 40, 40);
createImageBitmap(image, getSpriteAdder('tree'), 80, 0, 40, 40);
createImageBitmap(image, getSpriteAdder('hut'), 0, 40, 40, 40);
createImageBitmap(image, getSpriteAdder('apple'), 40, 40, 40, 40);
createImageBitmap(image, getSpriteAdder('snake'), 80, 40, 40, 40);
};
}
function runDemo() {
var canvas = document.querySelector('canvas#demo');
var context = canvas.getContext('2d');
context.drawImage(sprites.tree, 30, 10);
context.drawImage(sprites.snake, 70, 10);
}
loadMySprites(runDemo);