Scripts allow authors to add interactivity to their documents.
Authors are encouraged to use declarative alternatives to scripting where possible, as declarative mechanisms are often more maintainable, and many users disable scripting.
For example, instead of using script to show or hide a section to show more details, the
details element could be used.
Authors are also encouraged to make their applications degrade gracefully in the absence of scripting support.
For example, if an author provides a link in a table header to dynamically resort the table, the link could also be made to function without scripts by requesting the sorted table from the server.
script elementsrc
attribute, depends on the value of the type attribute, but must match
script content restrictions.src
attribute, the element must be either empty or contain only
script documentation that also matches script
content restrictions.src - Address of the resourcetype - Type of embedded resourcecharset - Character encoding of the external script resourceasync - Execute script asynchronouslydefer - Defer script executioncrossorigin - How the element handles crossorigin requestsinterface HTMLScriptElement : HTMLElement {
attribute DOMString src;
attribute DOMString type;
attribute DOMString charset;
attribute boolean async;
attribute boolean defer;
attribute DOMString crossOrigin;
attribute DOMString text;
};
The script element allows authors to include dynamic script and data blocks in
their documents. The element does not represent content for the
user.
When used to include dynamic scripts, the scripts may either be embedded inline or may be
imported from an external file using the src attribute. If
the language is not that described by "text/javascript", then the type attribute must be present, as described below. Whatever
language is used, the contents of the script element must conform with the
requirements of that language's specification.
When used to include data blocks (as opposed to scripts), the data must be embedded inline, the
format of the data must be given using the type attribute,
the src attribute must not be specified, and the contents of
the script element must conform to the requirements defined for the format used.
The type attribute gives the language of the
script or format of the data. If the attribute is present, its value must be a valid MIME
type. The charset parameter must not be specified. The default, which
is used if the attribute is absent, is "text/javascript".
The src attribute, if specified, gives the
address of the external script resource to use. The value of the attribute must be a valid
non-empty URL potentially surrounded by spaces identifying a script resource of the type
given by the type attribute, if the attribute is present, or
of the type "text/javascript", if the attribute is absent. A resource is a
script resource of a given type if that type identifies a scripting language and the resource
conforms with the requirements of that language's specification.
The charset attribute gives the character
encoding of the external script resource. The attribute must not be specified if the src attribute is not present. If the attribute is set, its value
must be an ASCII case-insensitive match for one of the labels of an encoding, and must specify the same encoding as
the charset parameter of the Content-Type
metadata of the external file, if any. [ENCODING]
The async and defer attributes are boolean attributes that indicate how the script should be executed. The defer and async attributes
must not be specified if the src attribute is not
present.
There are three possible modes that can be selected using these attributes. If the async attribute is present, then the script will be executed
asynchronously, as soon as it is available. If the async
attribute is not present but the defer attribute is
present, then the script is executed when the page has finished parsing. If neither attribute is
present, then the script is fetched and executed immediately, before the user agent continues
parsing the page.
The exact processing details for these attributes are, for mostly historical
reasons, somewhat non-trivial, involving a number of aspects of HTML. The implementation
requirements are therefore by necessity scattered throughout the specification. The algorithms
below (in this section) describe the core of this processing, but these algorithms reference and
are referenced by the parsing rules for script start and end tags in HTML, in foreign content,
and in XML, the rules for the document.write() method, the handling of scripting, etc.
The defer attribute may be specified even if the async attribute is specified, to cause legacy Web browsers that
only support defer (and not async) to fall back to the defer behavior instead of the synchronous blocking behavior that
is the default.
The crossorigin attribute is a
CORS settings attribute. It controls, for scripts that are obtained from other origins, whether error information will be exposed.
Changing the src, type, charset, async, defer, and crossorigin attributes dynamically has no direct effect;
these attribute are only used at specific times described below.
A script element has several associated pieces of state.
The first is a flag indicating whether or not the script block has been "already
started". Initially, script elements must have this flag unset (script blocks,
when created, are not "already started"). The cloning
steps for script elements must set the "already started" flag on the copy if
it is set on the element being cloned.
The second is a flag indicating whether the element was "parser-inserted".
Initially, script elements must have this flag unset. It is set by the HTML
parser and the XML parser on script elements they insert and
affects the processing of those elements.
The third is a flag indicating whether the element will "force-async". Initially,
script elements must have this flag set. It is unset by the HTML parser
and the XML parser on script elements they insert. In addition, whenever
a script element whose "force-async" flag is set has a async content attribute added, the element's
"force-async" flag must be unset.
The fourth is a flag indicating whether or not the script block is "ready to be
parser-executed". Initially, script elements must have this flag unset (script
blocks, when created, are not "ready to be parser-executed"). This flag is used only for elements
that are also "parser-inserted", to let the parser know when to execute the
script.
The last few pieces of state are the script block's type, the
script block's character encoding, and the script block's fallback character
encoding. They are determined when the script is prepared, based on the attributes on
the element at that time, and the Document of the script element.
When a script element that is not marked as being "parser-inserted"
experiences one of the events listed in the following list, the user agent must synchronously
prepare the script element:
script element gets inserted
into a document, at the time the node is inserted
according to the DOM, after any other script elements inserted at the same time that
are earlier in the Document in tree order.script element is in a Document and a node or
document fragment is inserted into the
script element, after any script elements inserted at that time.script element is in a Document and has a src attribute set where previously the element had no such
attribute.To prepare a script, the user agent must act as follows:
If the script element is marked as having "already started", then
the user agent must abort these steps at this point. The script is not executed.
If the element has its "parser-inserted" flag set, then set was-parser-inserted to true and unset the element's "parser-inserted" flag. Otherwise, set was-parser-inserted to false.
This is done so that if parser-inserted script elements fail to run
when the parser tries to run them, e.g. because they are empty or specify an unsupported
scripting language, another script can later mutate them and cause them to run again.
If was-parser-inserted is true and the element does not have an async attribute, then set the element's
"force-async" flag to true.
This is done so that if a parser-inserted script element fails to
run when the parser tries to run it, but it is later executed after a script dynamically updates
it, it will execute asynchronously even if the async
attribute isn't set.
If the element has no src attribute, and its child
nodes, if any, consist only of comment nodes and empty Text nodes, then the user
agent must abort these steps at this point. The script is not executed.
If the element is not in a Document, then the user agent must abort
these steps at this point. The script is not executed.
If either:
script element has a type attribute
and its value is the empty string, orscript element has no type attribute
but it has a language attribute and that
attribute's value is the empty string, orscript element has neither a type
attribute nor a language attribute, then...let the script block's type for this script element be "text/javascript".
Otherwise, if the script element has a type attribute, let the script block's type for this
script element be the value of that attribute with any leading or trailing
sequences of space characters removed.
Otherwise, the element has a non-empty language
attribute; let the script block's type for this script element be the
concatenation of the string "text/" followed by the value of the language attribute.
The language attribute is never
conforming, and is always ignored if there is a type
attribute present.
If the user agent does not support the scripting language given by the
script block's type for this script element, then the user agent must abort
these steps at this point. The script is not executed.
If was-parser-inserted is true, then flag the element as "parser-inserted" again, and set the element's "force-async" flag to false.
The user agent must set the element's "already started" flag.
The state of the element at this moment is later used to determine the script source.
If the element is flagged as "parser-inserted", but the element's
Document is not the Document of the parser that created the element,
then abort these steps.
If scripting is disabled for the script
element, then the user agent must abort these steps at this point. The script is not
executed.
The definition of scripting is disabled
means that, amongst others, the following scripts will not execute: scripts in
XMLHttpRequest's responseXML
documents, scripts in DOMParser-created documents, scripts in documents created by
XSLTProcessor's transformToDocument feature, and scripts
that are first inserted by a script into a Document that was created using the
createDocument() API. [XHR] [DOMPARSING] [DOM]
If the script element has an event
attribute and a for attribute, then run these substeps:
Let for be the value of the for
attribute.
Let event be the value of the event attribute.
Strip leading and trailing whitespace from event and for.
If for is not an ASCII case-insensitive match for the
string "window", then the user agent must abort these steps at this
point. The script is not executed.
If event is not an ASCII case-insensitive match for
either the string "onload" or the string "onload()", then the user agent must abort these steps at this point. The script
is not executed.
If the script element has a charset
attribute, then let the script block's character encoding for this
script element be the result of getting an encoding from the value of
the charset attribute.
Otherwise, let the script block's fallback character encoding for this
script element be the same as the
encoding of the document itself.
Only one of these two pieces of state is set.
If the element has a src content attribute, run these
substeps:
Let src be the value of the element's src attribute.
If src is the empty string, queue a task to fire
a simple event named error at the element, and abort
these steps.
Resolve src relative to the element.
If the previous step failed, queue a task to fire a simple
event named error at the element, and abort these
steps.
Do a potentially CORS-enabled fetch of the resulting
absolute URL, with the mode being the current state of the element's crossorigin content attribute, the origin being the origin of the script element's
Document, and the default origin behaviour set to taint.
The resource obtained in this fashion can be either CORS-same-origin or CORS-cross-origin. This only affects how error reporting happens.
For performance reasons, user agents may start fetching the script (as defined above) as
soon as the src attribute is set, instead, in the hope
that the element will be inserted into the document (and that the crossorigin attribute won't change value in the
meantime). Either way, once the element is inserted into the document, the load must have started as described in this
step. If the UA performs such prefetching, but the element is never inserted in the document,
or the src attribute is dynamically changed, or the crossorigin attribute is dynamically changed, then the
user agent will not execute the script so obtained, and the fetching process will have been
effectively wasted.
Then, the first of the following options that describes the situation must be followed:
src
attribute, and the element has a defer attribute, and
the element has been flagged as "parser-inserted", and the element does not have
an async attributeThe element must be added to the end of the list of scripts that will execute when the
document has finished parsing associated with the Document of the parser
that created the element.
The task that the networking task source places on the task queue once the fetching algorithm has completed must set the element's "ready to be parser-executed" flag. The parser will handle executing the script.
src attribute, and the element has been flagged as
"parser-inserted", and the element does not have an async attributeThe element is the pending parsing-blocking script of the
Document of the parser that created the element. (There can only be one such
script per Document at a time.)
The task that the networking task source places on the task queue once the fetching algorithm has completed must set the element's "ready to be parser-executed" flag. The parser will handle executing the script.
src attribute, and the element has been flagged as
"parser-inserted", and either the parser that created the script is
an XML parser or it's an HTML parser whose script nesting
level is not greater than one, and the Document of the HTML
parser or XML parser that created the script element has
a style sheet that is blocking scriptsThe element is the pending parsing-blocking script of the
Document of the parser that created the element. (There can only be one such
script per Document at a time.)
Set the element's "ready to be parser-executed" flag. The parser will handle executing the script.
src attribute, does not have an async attribute, and does not have the
"force-async" flag setThe element must be added to the end of the list of scripts that will execute in order
as soon as possible associated with the Document of the script
element at the time the prepare a script algorithm started.
The task that the networking task source places on the task queue once the fetching algorithm has completed must run the following steps:
If the element is not now the first element in the list of scripts that will execute in order as soon as possible to which it was added above, then mark the element as ready but abort these steps without executing the script yet.
Execution: Execute the script block corresponding to the first script element in this list of scripts that will execute in order as soon as possible.
Remove the first element from this list of scripts that will execute in order as soon as possible.
If this list of scripts that will execute in order as soon as possible is still not empty and the first entry has already been marked as ready, then jump back to the step labeled execution.
src
attributeThe element must be added to the set of scripts that will execute as soon as
possible of the Document of the script element at the time the
prepare a script algorithm started.
The task that the networking task source places on the task queue once the fetching algorithm has completed must execute the script block and then remove the element from the set of scripts that will execute as soon as possible.
Fetching an external script must delay the load event of the element's document until the task that is queued by the networking task source once the resource has been fetched (defined above) has been run.
The pending parsing-blocking script of a Document is used by the
Document's parser(s).
If a script element that blocks a parser gets moved to another
Document before it would normally have stopped blocking that parser, it nonetheless
continues blocking that parser until the condition that causes it to be blocking the parser no
longer applies (e.g. if the script is a pending parsing-blocking script because there
was a style sheet that is blocking scripts when it was parsed, but then the script is
moved to another Document before the style sheet loads, the script still blocks the
parser until the style sheets are all loaded, at which time the script executes and the parser is
unblocked).
When the user agent is required to execute a script block, it must run the following steps:
If the element is flagged as "parser-inserted", but the element's
Document is not the Document of the parser that created the element,
then abort these steps.
Jump to the appropriate set of steps from the list below:
Executing the script block must just consist of firing
a simple event named error at the element.
Executing the script block must consist of running the following steps. For the purposes of
these steps, the script is considered to be from an external file if, while the
prepare a script algorithm above was running for this script, the
script element had a src attribute
specified.
Initialise the script block's source as follows:
The contents of that file, interpreted as a Unicode string, are the script source.
To obtain the Unicode string, the user agent run the following steps:
If the resource's Content Type metadata, if any, specifies a character encoding, and the user agent supports that encoding, then let character encoding be that encoding, and jump to the bottom step in this series of steps.
If the algorithm above set the script block's character encoding, then let character encoding be that encoding, and jump to the bottom step in this series of steps.
Let character encoding be the script block's fallback character encoding.
If the specification for the script block's type gives specific rules for decoding files in that format to Unicode, follow them, using character encoding as the character encoding specified by higher-level protocols, if necessary.
Otherwise, decode the file to Unicode, using character encoding as the fallback encoding.
The decode algorithm overrides character encoding if the file contains a BOM.
The external file is the script source. When it is later executed, it must be interpreted in a manner consistent with the specification defining the language given by the script block's type.
The value of the text IDL attribute at the time
the element's "already started" flag was last set is the script source.
The child nodes of the script element at the time the element's
"already started" flag was last set are the script source.
Fire a simple event named beforescriptexecute that bubbles and is cancelable
at the script element.
If the event is canceled, then abort these steps.
If the script is from an external file, then increment the
ignore-destructive-writes counter of the script element's
Document. Let neutralised doc be that
Document.
Let old script element be the value to which the script
element's Document's currentScript object was most recently
initialized.
Initialise the script element's Document's currentScript object to the script
element.
Create a script, using the script block's source, the
URL from which the script was obtained, the script block's type as
the scripting language, and the script settings object of the
script element's Document's Window object.
If the script came from a resource that was fetched in the steps above, and the resource was CORS-cross-origin, then pass the muted errors flag to the create a script algorithm as well.
This is where the script is compiled and actually executed.
Initialise the script element's Document's currentScript object to old script
element.
Decrement the ignore-destructive-writes counter of neutralised doc, if it was incremented in the earlier step.
Fire a simple event named afterscriptexecute that bubbles (but is not
cancelable) at the script element.
If the script is from an external file, fire a simple event named load at the script element.
Otherwise, the script is internal; queue a task to fire a simple
event named load at the script
element.
The IDL attributes src, type, charset, defer, each must reflect the respective
content attributes of the same name.
The crossOrigin IDL attribute must
reflect the crossorigin content
attribute, limited to only known values.
The async IDL attribute controls whether the
element will execute asynchronously or not. If the element's "force-async" flag is
set, then, on getting, the async IDL attribute must return
true, and on setting, the "force-async" flag must first be unset, and then the
content attribute must be removed if the IDL attribute's new value is false, and must be set to
the empty string if the IDL attribute's new value is true. If the element's
"force-async" flag is not set, the IDL attribute must reflect
the async content attribute.
text [ = value ]Returns the contents of the element, ignoring child nodes that aren't Text
nodes.
Can be set, to replace the element's children with the given value.
The IDL attribute text must return a
concatenation of the contents of all the Text nodes that are children of the
script element (ignoring any other nodes such as comments or elements), in tree
order. On setting, it must act the same way as the textContent IDL attribute.
When inserted using the document.write()
method, script elements execute (typically synchronously), but when inserted using
innerHTML and outerHTML
attributes, they do not execute at all.
In this example, two script elements are used. One embeds an external script, and
the other includes some data.
<script src="game-engine.js"></script> <script type="text/x-game-map"> ........U.........e o............A....e .....A.....AAA....e .A..AAA...AAAAA...e </script>
The data in this case might be used by the script to generate the map of a video game. The data doesn't have to be used that way, though; maybe the map data is actually embedded in other parts of the page's markup, and the data block here is just used by the site's search engine to help users who are looking for particular features in their game maps.
The following sample shows how a script element can be used to define a function that is then
used by other parts of the document. It also shows how a script element can be used
to invoke script while the document is being parsed, in this case to initialise the form's
output.
<script>
function calculate(form) {
var price = 52000;
if (form.elements.brakes.checked)
price += 1000;
if (form.elements.radio.checked)
price += 2500;
if (form.elements.turbo.checked)
price += 5000;
if (form.elements.sticker.checked)
price += 250;
form.elements.result.value = price;
}
</script>
<form name="pricecalc" onsubmit="return false" onchange="calculate(this)">
<fieldset>
<legend>Work out the price of your car</legend>
<p>Base cost: £52000.</p>
<p>Select additional options:</p>
<ul>
<li><label><input type=checkbox name=brakes> Ceramic brakes (£1000)</label></li>
<li><label><input type=checkbox name=radio> Satellite radio (£2500)</label></li>
<li><label><input type=checkbox name=turbo> Turbo charger (£5000)</label></li>
<li><label><input type=checkbox name=sticker> "XZ" sticker (£250)</label></li>
</ul>
<p>Total: £<output name=result></output></p>
</fieldset>
<script>
calculate(document.forms.pricecalc);
</script>
</form>
A user agent is said to support the scripting language if each component of the script block's type is an ASCII case-insensitive match for the corresponding component in the MIME type string of a scripting language that the user agent implements.
The following lists the MIME type strings that user agents must recognize, and the languages to which they refer:
application/ecmascript"application/javascript"application/x-ecmascript"application/x-javascript"text/ecmascript"text/javascript"text/javascript1.0"text/javascript1.1"text/javascript1.2"text/javascript1.3"text/javascript1.4"text/javascript1.5"text/jscript"text/livescript"text/x-ecmascript"text/x-javascript"User agents may support other MIME types for other languages, but must not support other MIME types for the languages in the list above. User agents are not required to support the languages listed above.
The following MIME types (with or without parameters) must not be interpreted as scripting languages:
text/plain"
text/xml"
application/octet-stream"
application/xml"
These types are explicitly listed here because they are poorly-defined types that are nonetheless likely to be used as formats for data blocks, and it would be problematic if they were suddenly to be interpreted as script by a user agent.
When examining types to determine if they represent supported languages, user agents must not ignore MIME parameters. Types are to be compared including all parameters.
For example, types that include the charset parameter will
not be recognised as referencing any of the scripting languages listed above.
script elementsThe easiest and safest way to avoid the rather strange restrictions described in
this section is to always escape "<!--" as "<\!--", "<script" as "<\script", and "</script" as "<\/script" when these sequences appear in literals in scripts (e.g. in
strings, regular expressions, or comments), and to avoid writing code that uses such constructs in
expressions. Doing so avoids the pitfalls that the restrictions in this section are prone to
triggering: namely, that, for historical reasons, parsing of script blocks in HTML is
a strange and exotic practice that acts unintuitively in the face of these sequences.
The textContent of a script element must match the script production in the following ABNF, the character set for which is Unicode.
[ABNF]
script = outer *( comment-open inner comment-close outer ) outer = < any string that doesn't contain a substring that matches not-in-outer > not-in-outer = comment-open inner = < any string that doesn't contain a substring that matches not-in-inner > not-in-inner = comment-close / script-open comment-open = "<!--" comment-close = "-->" script-open = "<" s c r i p t tag-end s = %x0053 ; U+0053 LATIN CAPITAL LETTER S s =/ %x0073 ; U+0073 LATIN SMALL LETTER S c = %x0043 ; U+0043 LATIN CAPITAL LETTER C c =/ %x0063 ; U+0063 LATIN SMALL LETTER C r = %x0052 ; U+0052 LATIN CAPITAL LETTER R r =/ %x0072 ; U+0072 LATIN SMALL LETTER R i = %x0049 ; U+0049 LATIN CAPITAL LETTER I i =/ %x0069 ; U+0069 LATIN SMALL LETTER I p = %x0050 ; U+0050 LATIN CAPITAL LETTER P p =/ %x0070 ; U+0070 LATIN SMALL LETTER P t = %x0054 ; U+0054 LATIN CAPITAL LETTER T t =/ %x0074 ; U+0074 LATIN SMALL LETTER T tag-end = %x0009 ; "tab" (U+0009) tag-end =/ %x000A ; "LF" (U+000A) tag-end =/ %x000C ; "FF" (U+000C) tag-end =/ %x0020 ; U+0020 SPACE tag-end =/ %x002F ; "/" (U+002F) tag-end =/ %x003E ; ">" (U+003E)
When a script element contains script documentation, there are
further restrictions on the contents of the element, as described in the section below.
The following script illustrates this issue. Suppose you have a script that contains a string, as in:
var example = 'Consider this string: <!-- <script>'; console.log(example);
If one were to put this string directly in a script block, it would violate the
restrictions above:
<script> var example = 'Consider this string: <!-- <script>'; console.log(example); </script>
The bigger problem, though, and the reason why it would violate those restrictions, is that
actually the script would get parsed weirdly: the script block above is not terminated.
That is, what looks like a "</script>" end tag in this snippet is
actually still part of the script block. The script doesn't execute (since it's not
terminated); if it somehow were to execute, as it might if the markup looked as follows, it would
fail because the script (highlighted here) is not valid JavaScript:
<script> var example = 'Consider this string: <!-- <script>'; console.log(example); </script> <!-- despite appearances, this is actually part of the script still! --> <script> ... // this is the same script block still... </script>
What is going on here is that for legacy reasons, "<!--" and "<script" strings in script elements in HTML need to be balanced
in order for the parser to consider closing the block.
By escaping the problematic strings as mentioned at the top of this section, the problem is avoided entirely:
<script> var example = 'Consider this string: <\!-- <\script>'; console.log(example); </script> <!-- this is just a comment between script blocks --> <script> ... // this is a new script block </script>
It is possible for these sequences to naturally occur in script expressions, as in the following examples:
if (x<!--y) { ... }
if ( player<script ) { ... }
In such cases the characters cannot be escaped, but the expressions can be rewritten so that the sequences don't occur, as in:
if (x < !--y) { ... }
if (!--y > x) { ... }
if (!(--y) > x) { ... }
if (player < script) { ... }
if (script > player) { ... }
Doing this also avoids a different pitfall as well: for related historical reasons, the string "<!--" in JavaScript is actually treated as a line comment start, just like "//".
If a script element's src attribute is
specified, then the contents of the script element, if any, must be such that the
value of the text IDL attribute, which is derived from the
element's contents, matches the documentation production in the following
ABNF, the character set for which is Unicode. [ABNF]
documentation = *( *( space / tab / comment ) [ line-comment ] newline )
comment = slash star *( not-star / star not-slash ) 1*star slash
line-comment = slash slash *not-newline
; characters
tab = %x0009 ; "tab" (U+0009)
newline = %x000A ; "LF" (U+000A)
space = %x0020 ; U+0020 SPACE
star = %x002A ; "*" (U+002A)
slash = %x002F ; "/" (U+002F)
not-newline = %x0000-0009 / %x000B-10FFFF
; a Unicode character other than "LF" (U+000A)
not-star = %x0000-0029 / %x002B-10FFFF
; a Unicode character other than "*" (U+002A)
not-slash = %x0000-002E / %x0030-10FFFF
; a Unicode character other than "/" (U+002F)
This corresponds to putting the contents of the element in JavaScript comments.
This requirement is in addition to the earlier restrictions on the syntax of
contents of script elements.
This allows authors to include documentation, such as license information or API information,
inside their documents while still referring to external script files. The syntax is constrained
so that authors don't accidentally include what looks like valid script while also providing a
src attribute.
<script src="cool-effects.js"> // create new instances using: // var e = new Effect(); // start the effect using .play, stop using .stop: // e.play(); // e.stop(); </script>
script elements and XSLTThis section is non-normative.
This specification does not define how XSLT interacts with the script element.
However, in the absence of another specification actually defining this, here are some guidelines
for implementors, based on existing implementations:
When an XSLT transformation program is triggered by an <?xml-stylesheet?> processing instruction and the browser implements a
direct-to-DOM transformation, script elements created by the XSLT processor need to
be marked "parser-inserted" and run in document order (modulo scripts marked defer or async),
asynchronously while the transformation is occurring.
The XSLTProcessor.transformToDocument() method
adds elements to a Document that is not in a browsing context, and,
accordingly, any script elements they create need to have their "already
started" flag set in the prepare a script algorithm and never get executed
(scripting is disabled). Such script
elements still need to be marked "parser-inserted", though, such that their async IDL attribute will return false in the absence of an async content attribute.
The XSLTProcessor.transformToFragment() method
needs to create a fragment that is equivalent to one built manually by creating the elements
using document.createElementNS(). For instance,
it needs to create script elements that aren't "parser-inserted" and
that don't have their "already started" flag set, so that they will execute when the
fragment is inserted into a document.
The main distinction between the first two cases and the last case is that the first two
operate on Documents and the last operates on a fragment.
noscript elementhead element of an HTML document, if there are no ancestor noscript elements.noscript elements.head element: in any order, zero or more link elements, zero or more style elements, and zero or more meta elements.head element: transparent, but there must be no noscript element descendants.HTMLElement.The noscript element represents nothing if scripting is enabled, and represents its children if
scripting is disabled. It is used to present different
markup to user agents that support scripting and those that don't support scripting, by affecting
how the document is parsed.
When used in HTML documents, the allowed content model is as follows:
head element, if scripting is
disabled for the noscript elementThe noscript element must contain only link, style,
and meta elements.
head element, if scripting is enabled
for the noscript elementThe noscript element must contain only text, except that invoking the
HTML fragment parsing algorithm with
the noscript element as the context
element and the text contents as the input must result in a list of nodes
that consists only of link, style, and meta elements that
would be conforming if they were children of the noscript element, and no parse errors.
head elements, if scripting is
disabled for the noscript elementThe noscript element's content model is transparent, with the
additional restriction that a noscript element must not have a noscript
element as an ancestor (that is, noscript can't be nested).
head elements, if scripting is
enabled for the noscript elementThe noscript element must contain only text, except that the text must be such
that running the following algorithm results in a conforming document with no
noscript elements and no script elements, and such that no step in the
algorithm throws an exception or causes an HTML parser to flag a parse
error:
All these contortions are required because, for historical reasons, the
noscript element is handled differently by the HTML parser based on
whether scripting was enabled or not when the parser was
invoked.
The noscript element must not be used in XML documents.
The noscript element is only effective in the HTML
syntax, it has no effect in the XHTML syntax. This is because the way it works
is by essentially "turning off" the parser when scripts are enabled, so that the contents of the
element are treated as pure text and not as real elements. XML does not define a mechanism by
which to do this.
The noscript element has no other requirements. In particular, children of the
noscript element are not exempt from form submission, scripting, and so
forth, even when scripting is enabled for the element.
In the following example, a noscript element is
used to provide fallback for a script.
<form action="calcSquare.php">
<p>
<label for=x>Number</label>:
<input id="x" name="x" type="number">
</p>
<script>
var x = document.getElementById('x');
var output = document.createElement('p');
output.textContent = 'Type a number; it will be squared right then!';
x.form.appendChild(output);
x.form.onsubmit = function () { return false; }
x.oninput = function () {
var v = x.valueAsNumber;
output.textContent = v + ' squared is ' + v * v;
};
</script>
<noscript>
<input type=submit value="Calculate Square">
</noscript>
</form>
When script is disabled, a button appears to do the calculation on the server side. When script is enabled, the value is computed on-the-fly instead.
The noscript element is a blunt instrument. Sometimes, scripts might be enabled,
but for some reason the page's script might fail. For this reason, it's generally better to avoid
using noscript, and to instead design the script to change the page from being a
scriptless page to a scripted page on the fly, as in the next example:
<form action="calcSquare.php">
<p>
<label for=x>Number</label>:
<input id="x" name="x" type="number">
</p>
<input id="submit" type=submit value="Calculate Square">
<script>
var x = document.getElementById('x');
var output = document.createElement('p');
output.textContent = 'Type a number; it will be squared right then!';
x.form.appendChild(output);
x.form.onsubmit = function () { return false; }
x.oninput = function () {
var v = x.valueAsNumber;
output.textContent = v + ' squared is ' + v * v;
};
var submit = document.getElementById('submit');
submit.parentNode.removeChild(submit);
</script>
</form>
The above technique is also useful in XHTML, since noscript is not supported in
the XHTML syntax.
template elementcolgroup element that doesn't have a span attribute.ol and ul elements.dl elements.figure elements.ruby elements.object elements.video and audio elements.table elements.colgroup elements.thead, tbody, and tfoot elements.tr elements.fieldset elements.select elements.details elements.menu elements whose type attribute is in the popup menu state.interface HTMLTemplateElement : HTMLElement {
readonly attribute DocumentFragment content;
};
The template element is used to declare fragments of HTML that can be cloned and
inserted in the document by script.
Templates provide a method for declaring inert DOM subtrees and manipulating them to instantiate document fragments with identical contents.
When web pages dynamically alter the contents of their documents (e.g. in response to user interaction or new data arriving from the server), it is common that they require fragments of HTML which may require further modification before use, such as the insertion of values appropriate for the usage context.
The template element allows for the declaration of document fragments which are
unused by the document when loaded, but are parsed as HTML and are available at runtime for use by
the web page.
In a rendering, the template element represents nothing.
contentReturns the contents of the template, which are stored in a
DocumentFragment associated with a different Document so as to avoid
the template contents interfering with the main Document. (For
example, this avoids form controls from being submitted, scripts from executing, and so
forth.)
Each template element has an associated DocumentFragment object that
is its template contents. When a template element is created, the user
agent must run the following steps to establish the template contents:
Let doc be the template element's ownerDocument's appropriate template contents owner
document.
Create a DocumentFragment object whose ownerDocument is doc.
Set the template element's template contents to the newly
created DocumentFragment object.
A Document doc's appropriate template contents owner
document is the Document returned by the following algorithm:
If doc is not a Document created by this algorithm, run
these substeps:
If doc does not yet have an associated inert template document then run these substeps:
Let new doc be a new Document (that does not have a
browsing context). This is "a Document created by this algorithm"
for the purposes of the step above.
If doc is an HTML document, mark new doc as an HTML document also.
Let doc's associated inert template document be new doc.
Set doc to doc's associated inert template document.
Each Document not created by this algorithm thus gets a single
Document to act as its proxy for owning the template contents of all
its template elements, so that they aren't in a browsing context and
thus remain inert (e.g. scripts do not run). Meanwhile, template elements inside
Document objects that are created by this algorithm just reuse the same
Document owner for their contents.
Return doc.
When a template element changes ownerDocument, the user agent must run the following
steps:
Let doc be the template element's new ownerDocument's appropriate template contents owner
document.
Adopt the template element's
template contents (a DocumentFragment object) into doc.
The content IDL attribute must return the
template element's template contents.
The cloning steps for a template
element node being cloned to a copy copy must run the
following steps:
If the clone children flag is not set in the calling clone algorithm, abort these steps.
Let copied contents be the result of cloning all the children of node's
template contents, with ownerDocument set to copy's template contents's ownerDocument, and with the clone children
flag set.
Append copied contents to copy's template contents.
In this example, a script populates a table with data from a data structure, using a
template to provide the element structure instead of manually generating the
structure from markup.
<!DOCTYPE html>
<title>Cat data</title>
<script>
// Data is hard-coded here, but could come from the server
var data = [
{ name: 'Pillar', color: 'Ticked Tabby', sex: 'Female (neutered)', legs: 3 },
{ name: 'Hedral', color: 'Tuxedo', sex: 'Male (neutered)', legs: 4 },
];
</script>
<table>
<thead>
<tr>
<th>Name <th>Color <th>Sex <th>Legs
<tbody>
<template id="row">
<tr><td><td><td><td>
</template>
</table>
<script>
var template = document.querySelector('#row');
for (var i = 0; i < data.length; i += 1) {
var cat = data[i];
var clone = template.content.cloneNode(true);
var cells = clone.querySelectorAll('td');
cells[0].textContent = cat.name;
cells[1].textContent = cat.color;
cells[2].textContent = cat.sex;
cells[3].textContent = cat.legs;
template.parentNode.appendChild(clone);
}
</script>
template elements with XSLT and XPathThis section is non-normative.
This specification does not define how XSLT and XPath interact with the template
element. However, in the absence of another specification actually defining this, here are some
guidelines for implementors, which are intended to be consistent with other processing described
in this specification:
An XSLT processor based on an XML parser that acts as described
in this specification needs to act as if template elements contain as
descendants their template contents for the purposes of the transform.
An XSLT processor that outputs a DOM needs to ensure that nodes that would go into a
template element are instead placed into the element's template
contents.
XPath evaluation using the XPath DOM API when applied to a Document parsed
using the HTML parser or the XML parser described in this specification
needs to ignore template contents.
canvas elementwidthheighttypedef (CanvasRenderingContext2D or WebGLRenderingContext) RenderingContext;
interface HTMLCanvasElement : HTMLElement {
attribute unsigned long width;
attribute unsigned long height;
RenderingContext? getContext(DOMString contextId, any... arguments);
boolean probablySupportsContext(DOMString contextId, any... arguments);
void setContext(RenderingContext context);
CanvasProxy transferControlToProxy();
DOMString toDataURL(optional DOMString type, any... arguments);
void toBlob(FileCallback? _callback, optional DOMString type, any... arguments);
};
The canvas element provides scripts with a resolution-dependent bitmap canvas,
which can be used for rendering graphs, game graphics, art, or other visual images on the fly.
Authors should not use the canvas element in a document when a more suitable
element is available. For example, it is inappropriate to use a canvas element to
render a page heading: if the desired presentation of the heading is graphically intense, it
should be marked up using appropriate elements (typically h1) and then styled using
CSS and supporting technologies such as Web Components.
When authors use the canvas element, they must also provide content that, when
presented to the user, conveys essentially the same function or purpose as the
canvas' bitmap. This content may be placed as content of the canvas
element. The contents of the canvas element, if any, are the element's fallback
content.
In interactive visual media, if scripting is enabled for
the canvas element, and if support for canvas elements has been enabled,
the canvas element represents embedded content consisting
of a dynamically created image, the element's bitmap.
In non-interactive, static, visual media, if the canvas element has been
previously associated with a rendering context (e.g. if the page was viewed in an interactive
visual medium and is now being printed, or if some script that ran during the page layout process
painted on the element), then the canvas element represents
embedded content with the element's current bitmap and size. Otherwise, the element
represents its fallback content instead.
In non-visual media, and in visual media if scripting is
disabled for the canvas element or if support for canvas elements
has been disabled, the canvas element represents its fallback
content instead.
When a canvas element represents embedded content, the
user can still focus descendants of the canvas element (in the fallback
content). When an element is focused, it is the target of keyboard interaction events (even
though the element itself is not visible). This allows authors to make an interactive canvas
keyboard-accessible: authors should have a one-to-one mapping of interactive regions to focusable
elements in the fallback content. (Focus has no effect on mouse interaction events.)
[DOMEVENTS]
The canvas element has two attributes to control the size of the element's bitmap:
width and height. These attributes, when specified, must have
values that are valid non-negative integers. The rules for parsing non-negative integers must be used to obtain their
numeric values. If an attribute is missing, or if parsing its value returns an error, then the
default value must be used instead. The width
attribute defaults to 300, and the height attribute
defaults to 150.
The intrinsic dimensions of the canvas element when it represents
embedded content are equal to the dimensions of the element's bitmap.
The user agent must use a square pixel density consisting of one pixel of image data per
coordinate space unit for the bitmaps of a canvas and its rendering contexts.
A canvas element can be sized arbitrarily by a style sheet, its
bitmap is then subject to the 'object-fit' CSS property. [CSSIMAGES]
The bitmaps of canvas elements, as well as some of the bitmaps of rendering
contexts, such as those described in the HTML Canvas 2D Context specification
[CANVAS2D],
have an origin-clean flag, which can
be set to true or false. Initially, when the canvas element is created, its bitmap's
origin-clean flag must be set to true.
A canvas bitmap can also have a hit region list, as described in the
CanvasRenderingContext2D section below.
A canvas element can have a rendering context bound to it. Initially, it does not
have a bound rendering context. To keep track of whether it has a rendering context or not, and
what kind of rendering context it is, a canvas also has a canvas context mode, which is initially none but can be changed to either direct-2d, direct-webgl, indirect, or proxied by algorithms defined in this specification.
When its canvas context mode is none, a canvas element has no rendering context,
and its bitmap must be fully transparent black with an intrinsic width equal to the numeric value
of the element's width attribute and an intrinsic height
equal to the numeric value of the element's height
attribute, those values being interpreted in CSS pixels, and being updated as the attributes are
set, changed, or removed.
When a canvas element represents embedded content, it provides
a paint source whose width is the element's intrinsic width, whose height is the element's
intrinsic height, and whose appearance is the element's bitmap.
Whenever the width and height content attributes are set, removed, changed, or
redundantly set to the value they already have, if the canvas context mode is direct-2d, the user agent must set bitmap dimensions to the numeric values of
the width and height content attributes.
The width and height IDL attributes must reflect the
respective content attributes of the same name, with the same defaults.
getContext(contextId [, ... ] )Returns an object that exposes an API for drawing on the canvas. The first argument specifies
the desired API, either "2d" or "webgl". Subsequent arguments are handled by that API.
The list of defined contexts is given on the WHATWG Wiki CanvasContexts page. [WHATWGWIKI]
Example contexts are the "2d" [CANVAS2D] and the "webgl" context [WEBGL].
Returns null if the given context ID is not supported or if the canvas has already been
initialized with some other (incompatible) context type (e.g. trying to get a "2d" context after getting a "webgl" context).
Throws an InvalidStateError exception if the setContext() or transferControlToProxy() methods have been
used.
probablySupportsContext(contextId [, ... ] )Returns false if calling getContext() with the
same arguments would definitely return null, and true otherwise.
This return value is not a guarantee that getContext() will or will not return an object, as
conditions (e.g. availability of system resources) can vary over time.
Throws an InvalidStateError exception if the setContext() or transferControlToProxy() methods have been
used.
setContext(context)Sets the canvas' rendering context to the given object.
Throws an InvalidStateError exception if the getContext() or transferControlToProxy() methods have been
used.
There are two ways for a canvas element to acquire a rendering context: the
canvas element can provide one via the getContext() method, and one can be assigned to it via the
setContext() method. In addition, the whole issue of a
rendering context can be taken out of the canvas element's hands and passed to a
CanvasProxy object, which itself can then be assigned a rendering context using its
setContext() method.
These three methods are mutually exclusive; calling any of the three makes the other two start
throwing InvalidStateError exceptions when called.
Each rendering context has a context bitmap mode, which is one of fixed, unbound, or bound. Initially, rendering contexts must be in the unbound mode.
The getContext(contextId, arguments...) method of the canvas element, when invoked,
must run the steps in the cell of the following table whose column header describes the
canvas element's canvas context mode
and whose row header describes the method's first argument.
| none | direct-2d | direct-webgl | indirect | proxied | |
|---|---|---|---|---|---|
"2d"
|
Set the canvas element's context
mode to direct-2d, obtain a
CanvasRenderingContext2D object as defined in the HTML Canvas 2D Context
specification [CANVAS2D], set the obtained
CanvasRenderingContext2D object's
context bitmap mode to
fixed, and return the
CanvasRenderingContext2D object
| Return the same object as was return the last time the method was invoked with this same argument. | Return null. |
Throw an InvalidStateError exception.
|
Throw an InvalidStateError exception.
|
"webgl", if the user agent supports the WebGL feature in its current configuration
|
Follow the instructions given in the WebGL specification's Context Creation section to
obtain either a WebGLRenderingContext or null; if the returned value is null,
then return null and abort these steps, otherwise, set the canvas element's context mode to direct-webgl, set the new
WebGLRenderingContext object's context bitmap mode to fixed, and return the WebGLRenderingContext
object‡ [WEBGL]
| Return null. | Return the same object as was return the last time the method was invoked with this same argument. |
Throw an InvalidStateError exception.
|
Throw an InvalidStateError exception.
|
| A vendor-specific extension* | Behave as defined for the extension. | Behave as defined for the extension. | Behave as defined for the extension. |
Throw an InvalidStateError exception.
|
Throw an InvalidStateError exception.
|
| An unsupported value† | Return null. | Return null. | Return null. |
Throw an InvalidStateError exception.
|
Throw an InvalidStateError exception.
|
* Vendors may define experimental contexts using the syntax vendorname-context, for example,
moz-3d.
† For example, the "webgl" value in the case of a user agent having exhausted the
graphics hardware's abilities and having no software fallback implementation.
‡ The second (and subsequent) argument(s) to the method, if any, are ignored in all cases except this one. See the WebGL specification for details.
The probablySupportsContext(contextId,
arguments...) method of the canvas element, when
invoked, must return false if calling getContext() on
the same object and with the same arguments would definitely return null at this time, and true
otherwise.
The setContext(context) method of the canvas element, when invoked, must
run the following steps:
If the canvas element's canvas
context mode is neither none nor indirect, throw an InvalidStateError
exception and abort these steps.
If context's context
bitmap mode is fixed, then throw an
InvalidStateError exception and abort these steps.
If context's context bitmap mode is bound, then run context's unbinding steps and set its context's context bitmap mode to unbound.
Run context's binding
steps to bind it to this canvas element.
Set the canvas element's context
mode to indirect and the context's context bitmap
mode to bound.
toDataURL( [ type, ... ] )Returns a data: URL for the image in
the canvas.
The first argument, if provided, controls the type of the image to be returned (e.g. PNG or
JPEG). The default is image/png; that type is also used if the given type
isn't supported. The other arguments are specific to the type, and control the way that the
image is generated, as given in the table
below.
When trying to use types other than "image/png", authors can check if the image
was really returned in the requested format by checking to see if the returned string starts
with one of the exact strings "data:image/png," or "data:image/png;". If it does, the image is PNG, and thus the requested type was
not supported. (The one exception to this is if the canvas has either no height or no width, in
which case the result might simply be "data:,".)
toBlob(callback [, type, ... ] )Creates a Blob object representing a file containing the image in the canvas,
and invokes a callback with a handle to that object.
The second argument, if provided, controls the type of the image to be returned (e.g. PNG or
JPEG). The default is image/png; that type is also used if the given type
isn't supported. The other arguments are specific to the type, and control the way that the
image is generated, as given in the table
below.
The toDataURL() method must run the
following steps:
If the canvas element's bitmap's origin-clean flag is set to false, throw a
SecurityError exception and abort these steps.
If the canvas element's bitmap has no pixels (i.e. either its horizontal
dimension or its vertical dimension is zero) then return the string "data:," and abort these steps. (This is the shortest data: URL; it represents the empty string in a text/plain resource.)
Let file be a
serialization of the canvas element's bitmap as a file, using the method's
arguments (if any) as the arguments.
The toBlob() method must run the following
steps:
If the canvas element's bitmap's origin-clean flag is set to false, throw a
SecurityError exception and abort these steps.
Let callback be the first argument.
Let arguments be the second and subsequent arguments to the method, if any.
If the canvas element's bitmap has no pixels (i.e. either its horizontal
dimension or its vertical dimension is zero) then let result be null.
Otherwise, let result be a Blob object representing a serialization of the canvas
element's bitmap as a file, using arguments. [FILEAPI]
Return, but continue running these steps asynchronously.
If callback is null, abort these steps.
Queue a task to invoke the FileCallback callback with result as its argument. The task
source for this task is the canvas blob serialization task source.
Since DOM nodes cannot be accessed across worker boundaries, a proxy object is needed to enable
workers to render to canvas elements in Documents.
[Exposed=Window,Worker]
interface CanvasProxy {
void setContext(RenderingContext context);
};
// CanvasProxy implements Transferable;
transferControlToProxy()Returns a CanvasProxy object that can be used to transfer control for this
canvas over to another document (e.g. an iframe from another origin)
or to a worker.
Throws an InvalidStateError exception if the getContext() or setContext() methods have been used.
setContext(context)Sets the CanvasProxy object's canvas element's rendering context to
the given object.
Throws an InvalidStateError exception if the CanvasProxy has been
transfered.
The transferControlToProxy()
method of the canvas element, when invoked, must run the following steps:
If the canvas element's canvas
context mode is not none, throw an
InvalidStateError exception and abort these steps.
Set the canvas element's context
mode to proxied.
Return a CanvasProxy object bound to this canvas
element.
A CanvasProxy object can be neutered (like any Transferable object),
meaning it can no longer be transferred, and
can be disabled, meaning it can no longer be bound
to rendering contexts. When first created, a CanvasProxy object must be neither.
A CanvasProxy is created with a link to a canvas element. A
CanvasProxy object that has not been disabled must have a strong reference to its canvas
element.
The setContext(context) method of CanvasProxy objects, when invoked,
must run the following steps:
If the CanvasProxy object has been disabled, throw an InvalidStateError
exception and abort these steps.
If the CanvasProxy object has not been neutered, then neuter it.
If context's context
bitmap mode is fixed, then throw an
InvalidStateError exception and abort these steps.
If context's context bitmap mode is bound, then run context's unbinding steps and set its context's context bitmap mode to unbound.
Run context's binding
steps to bind it to this CanvasProxy object's canvas
element.
Set the context's context bitmap mode to bound.
To transfer a
CanvasProxy object old to a new owner owner,
a user agent must create a new CanvasProxy object linked to the same
canvas element as old, thus obtaining new,
must neuter and disable the old object, and must
finally return new.
Here is a clock implemented on a worker. First, the main page:
<!DOCTYPE HTML>
<title>Clock</title>
<canvas></canvas>
<script>
var canvas = document.getElementsByTagName('canvas')[0];
var proxy = canvas.transferControlToProxy();
var worker = new Worker('clock.js');
worker.postMessage(proxy, [proxy]);
</script>
Second, the worker:
onmessage = function (event) {
var context = new CanvasRenderingContext2D();
event.data.setContext(context); // event.data is the CanvasProxy object
setInterval(function () {
context.clearRect(0, 0, context.width, context.height);
context.fillText(new Date(), 0, 100);
context.commit();
}, 1000);
};
The canvas APIs must perform color correction at only two points: when rendering
images with their own gamma correction and color space information onto a bitmap, to convert the
image to the color space used by the bitmaps (e.g. using the 2D Context's drawImage() method with an HTMLImageElement
object), and when rendering the actual canvas bitmap to the output device.
Thus, in the 2D context, colors used to draw shapes onto the canvas will exactly
match colors obtained through the getImageData() method.
The toDataURL() method must not include color space
information in the resources they return. Where the output format allows it, the color of pixels
in resources created by toDataURL() must match those
returned by the getImageData() method.
In user agents that support CSS, the color space used by a canvas element must
match the color space used for processing any colors for that element in CSS.
The gamma correction and color space information of images must be handled in such a way that
an image rendered directly using an img element would use the same colors as one
painted on a canvas element that is then itself rendered. Furthermore, the rendering
of images that have no color correction information (such as those returned by the toDataURL() method) must be rendered with no color
correction.
Thus, in the 2D context, calling the drawImage() method to render the output of the toDataURL() method to the canvas, given the appropriate
dimensions, has no visible effect.
When a user agent is to create a serialization of the bitmap as a file, optionally with some given arguments, and optionally with a native flag set, it must create an image file in the format given by the first value of arguments, or, if there are no arguments, in the PNG format. [PNG]
If the native flag is set, or if the bitmap has one pixel per coordinate space unit, then the image file must have the same pixel data (before compression, if applicable) as the bitmap, and if the file format used supports encoding resolution metadata, the resolution of that bitmap (device pixels per coordinate space units being interpreted as image pixels per CSS pixel) must be given as well.
Otherwise, the image file's pixel data must be the bitmap's pixel data scaled to one image pixel per coordinate space unit, and if the file format used supports encoding resolution metadata, the resolution must be given as 96dpi (one image pixel per CSS pixel).
If arguments is not empty, the first value must be interpreted as a MIME type giving the format to use. If the type has any parameters, it must be treated as not supported.
For example, the value "image/png" would mean to generate a PNG
image, the value "image/jpeg" would mean to generate a JPEG image, and the value
"image/svg+xml" would mean to generate an SVG image (which would require that the
user agent track how the bitmap was generated, an unlikely, though potentially awesome,
feature).
User agents must support PNG ("image/png"). User agents may support other types.
If the user agent does not support the requested type, it must create the file using the PNG
format. [PNG]
User agents must convert the provided type to ASCII lowercase before establishing if they support that type.
For image types that do not support an alpha channel, the serialised image must be the bitmap image composited onto a solid black background using the source-over operator.
If the first argument in arguments gives a type corresponding to one of the types given in the first column of the following table, and the user agent supports that type, then the subsequent arguments, if any, must be treated as described in the second cell of that row.
| Type | Other arguments | Reference |
|---|---|---|
image/jpeg
| The second argument, if it is a number in the range 0.0 to 1.0 inclusive, must be treated as the desired quality level. If it is not a number or is outside that range, the user agent must use its default value, as if the argument had been omitted. | [JPEG] |
For the purposes of these rules, an argument is considered to be a number if it is converted to
an IDL double value by the rules for handling arguments of type any in the
Web IDL specification. [WEBIDL]
Other arguments must be ignored and must not cause the user agent to throw an exception. A future version of this specification will probably define other parameters to be passed to these methods to allow authors to more carefully control compression settings, image metadata, etc.
canvas elementsThis section is non-normative.
Information leakage can occur if scripts from one origin can access information (e.g. read pixels) from images from another origin (one that isn't the same).
To mitigate this, bitmaps used with canvas elements are defined to have a flag
indicating whether they are origin-clean. All
bitmaps start with their origin-clean set to
true. The flag is set to false when cross-origin images or fonts are used.
The toDataURL(), toBlob(), and getImageData() methods check the flag and will
throw a SecurityError exception rather than leak cross-origin data.
The flag can be reset in certain situations; for example, when a
CanvasRenderingContext2D is bound to a new canvas, the bitmap is cleared
and its flag reset.