This specification refers to both HTML and XML attributes and DOM attributes, often in the same context. When it is not clear which is being referred to, they are referred to as content attributes for HTML and XML attributes, and DOM attributes for those from the DOM. Similarly, the term "properties" is used for both ECMAScript object properties and CSS properties. When these are ambiguous they are qualified as object properties and CSS properties respectively.
The term HTML documents is sometimes used in contrast with XML documents to specifically mean documents that were parsed using an HTML parser (as opposed to using an XML parser or created purely through the DOM).
Generally, when the specification states that a feature applies to HTML or XHTML, it also includes the other. When a feature specifically only applies to one of the two languages, it is called out by explicitly stating that it does not apply to the other format, as in "for HTML, ... (this does not apply to XHTML)".
This specification uses the term document to refer to any use of HTML, ranging from short static documents to long essays or reports with rich multimedia, as well as to fully-fledged interactive applications.
For simplicity, terms such as shown, displayed, and visible might sometimes be used when referring to the way a document is rendered to the user. These terms are not meant to imply a visual medium; they must be considered to apply to other media in equivalent ways.
Some of the algorithms in this specification, for historical reasons, require the user agent to pause until some condition has been met. While a user agent is paused, it must ensure that no scripts execute (e.g. no event handlers, no timers, etc). User agents should remain responsive to user input while paused, however, albeit without letting the user interact with Web pages where that would involve invoking any script.
To ease migration from HTML to XHTML, UAs
conforming to this specification will place elements in HTML in the
http://www.w3.org/1999/xhtml
namespace, at least for
the purposes of the DOM and CSS. The term "elements in the HTML
namespace", or "HTML elements" for short, when used
in this specification, thus refers to both HTML and XHTML
elements.
Unless otherwise stated, all elements defined or mentioned in
this specification are in the
http://www.w3.org/1999/xhtml
namespace, and all
attributes defined or mentioned in this specification have no
namespace (they are in the per-element partition).
When an XML name, such as an attribute or element name, is
referred to in the form prefix:localName
, as in xml:id
or
svg:rect
, it refers to a name with the local name localName and the namespace given by the prefix, as
defined by the following table:
xml
http://www.w3.org/XML/1998/namespace
html
http://www.w3.org/1999/xhtml
svg
http://www.w3.org/2000/svg
Attribute names are said to be XML-compatible if they
match the Name
production defined in XML, they contain no
U+003A COLON (:) characters, and their first three characters are
not an ASCII case-insensitive match for the string
"xml
". [XML]
The term root element, when not explicitly qualified as referring to the document's root element, means the furthest ancestor element node of whatever node is being discussed, or the node itself if it has no ancestors. When the node is a part of the document, then that is indeed the document's root element; however, if the node is not currently part of the document tree, the root element will be an orphaned node.
A node's home subtree is the subtree rooted at that node's root element.
The Document
of a Node
(such as an
element) is the Document
that the Node
's
ownerDocument
DOM attribute returns.
An element is said to have been inserted into a document when its root
element changes and is now the document's root
element. If a Node
is in a Document
then that Document
is always the Node
's
Document
, and the Node
's ownerDocument
DOM attribute thus always returns that
Document
.
The term tree order means a pre-order, depth-first
traversal of DOM nodes involved (through the parentNode
/childNodes
relationship).
When it is stated that some element or attribute is ignored, or treated as some other value, or handled as if it was something else, this refers only to the processing of the node after it is in the DOM. A user agent must not mutate the DOM in such situations.
The term text node refers to any Text
node, including CDATASection
nodes; specifically, any
Node
with node type TEXT_NODE
(3)
or CDATA_SECTION_NODE
(4). [DOM3CORE]
The construction "a Foo
object", where
Foo
is actually an interface, is sometimes used instead
of the more accurate "an object implementing the interface
Foo
".
A DOM attribute is said to be getting when its value is being retrieved (e.g. by author script), and is said to be setting when a new value is assigned to it.
If a DOM object is said to be live, then that means that any attributes returning that object must always return the same object (not a new object each time), and the attributes and methods on that object must operate on the actual underlying data, not a snapshot of the data.
The terms fire and dispatch are used interchangeably in the context of events, as in the DOM Events specifications. [DOM3EVENTS]
The term plugin is used to mean any content handler, typically a third-party content handler, for Web content types that are not supported by the user agent natively, or for content types that do not expose a DOM, that supports rendering the content as part of the user agent's interface.
One example of a plugin would be a PDF viewer that is instantiated in a browsing context when the user navigates to a PDF file. This would count as a plugin regardless of whether the party that implemented the PDF viewer component was the same as that which implemented the user agent itself. However, a PDF viewer application that launches separate from the user agent (as opposed to using the same interface) is not a plugin by this definition.
This specification does not define a mechanism for interacting with plugins, as it is expected to be user-agent- and platform-specific. Some UAs might opt to support a plugin mechanism such as the Netscape Plugin API; others might use remote content converters or have built-in support for certain types. [NPAPI]
Browsers should take extreme care when interacting with external content intended for plugins. When third-party software is run with the same privileges as the user agent itself, vulnerabilities in the third-party software become as dangerous as those in the user agent.
An ASCII-compatible character encoding is one that is a superset of US-ASCII (specifically, ANSI_X3.4-1968) for bytes in the set 0x09, 0x0A, 0x0C, 0x0D, 0x20 - 0x22, 0x26, 0x27, 0x2C - 0x3F, 0x41 - 0x5A, and 0x61 - 0x7A.
All diagrams, examples, and notes in this specification are non-normative, as are all sections explicitly marked non-normative. Everything else in this specification is normative.
The key words "MUST", "MUST NOT", "REQUIRED", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in the normative parts of this document are to be interpreted as described in RFC2119. For readability, these words do not appear in all uppercase letters in this specification. [RFC2119]
Requirements phrased in the imperative as part of algorithms (such as "strip any leading space characters" or "return false and abort these steps") are to be interpreted with the meaning of the key word ("must", "should", "may", etc) used in introducing the algorithm.
This specification describes the conformance criteria for user agents (relevant to implementors) and documents (relevant to authors and authoring tool implementors).
There is no implied relationship between document conformance requirements and implementation conformance requirements. User agents are not free to handle non-conformant documents as they please; the processing model described in this specification applies to implementations regardless of the conformity of the input documents.
User agents fall into several (overlapping) categories with different conformance requirements.
Web browsers that support XHTML must process elements and attributes from the HTML namespace found in XML documents as described in this specification, so that users can interact with them, unless the semantics of those elements have been overridden by other specifications.
A conforming XHTML processor would, upon
finding an XHTML script
element in an XML document,
execute the script contained in that element. However, if the
element is found within a transformation expressed in XSLT
(assuming the user agent also supports XSLT), then the processor
would instead treat the script
element as an opaque
element that forms part of the transform.
Web browsers that support HTML must
process documents labeled as text/html
as described
in this specification, so that users can interact with them.
User agents that support scripting must also be conforming implementations of the IDL fragments in this specification, as described in the WebIDL specification. [WebIDL]
User agents that process HTML and XHTML documents purely to render non-interactive versions of them must comply to the same conformance criteria as Web browsers, except that they are exempt from requirements regarding user interaction.
Typical examples of non-interactive presentation user agents are printers (static UAs) and overhead displays (dynamic UAs). It is expected that most static non-interactive presentation user agents will also opt to lack scripting support.
A non-interactive but dynamic presentation UA would still execute scripts, allowing forms to be dynamically submitted, and so forth. However, since the concept of "focus" is irrelevant when the user cannot interact with the document, the UA would not need to support any of the focus-related DOM APIs.
Implementations that do not support scripting (or which have their scripting features disabled entirely) are exempt from supporting the events and DOM interfaces mentioned in this specification. For the parts of this specification that are defined in terms of an events model or in terms of the DOM, such user agents must still act as if events and the DOM were supported.
Scripting can form an integral part of an application. Web browsers that do not support scripting, or that have scripting disabled, might be unable to fully convey the author's intent.
Conformance checkers must verify that a document conforms to
the applicable conformance criteria described in this
specification. Automated conformance checkers are exempt from
detecting errors that require interpretation of the author's
intent (for example, while a document is non-conforming if the
content of a blockquote
element is not a quote,
conformance checkers running without the input of human judgement
do not have to check that blockquote
elements only
contain quoted material).
Conformance checkers must check that the input document conforms when parsed without a browsing context (meaning that no scripts are run, and that the parser's scripting flag is disabled), and should also check that the input document conforms when parsed with a browsing context in which scripts execute, and that the scripts never cause non-conforming states to occur other than transiently during script execution itself. (This is only a "SHOULD" and not a "MUST" requirement because it has been proven to be impossible. [HALTINGPROBLEM])
The term "HTML5 validator" can be used to refer to a conformance checker that itself conforms to the applicable requirements of this specification.
XML DTDs cannot express all the conformance requirements of this specification. Therefore, a validating XML processor and a DTD cannot constitute a conformance checker. Also, since neither of the two authoring formats defined in this specification are applications of SGML, a validating SGML system cannot constitute a conformance checker either.
To put it another way, there are three types of conformance criteria:
A conformance checker must check for the first two. A simple DTD-based validator only checks for the first class of errors and is therefore not a conforming conformance checker according to this specification.
Applications and tools that process HTML and XHTML documents for reasons other than to either render the documents or check them for conformance should act in accordance to the semantics of the documents that they process.
A tool that generates document outlines but increases the nesting level for each paragraph and does not increase the nesting level for each section would not be conforming.
Authoring tools and markup generators must generate conforming documents. Conformance criteria that apply to authors also apply to authoring tools, where appropriate.
Authoring tools are exempt from the strict requirements of using elements only for their specified purpose, but only to the extent that authoring tools are not yet able to determine author intent.
For example, it is not conforming to use an
address
element for arbitrary contact information;
that element can only be used for marking up contact information
for the author of the document or section. However, since an
authoring tool is likely unable to determine the difference, an
authoring tool is exempt from that requirement.
In terms of conformance checking, an editor is therefore required to output documents that conform to the same extent that a conformance checker will verify.
When an authoring tool is used to edit a non-conforming document, it may preserve the conformance errors in sections of the document that were not edited during the editing session (i.e. an editing tool is allowed to round-trip erroneous content). However, an authoring tool must not claim that the output is conformant if errors have been so preserved.
Authoring tools are expected to come in two broad varieties: tools that work from structure or semantic data, and tools that work on a What-You-See-Is-What-You-Get media-specific editing basis (WYSIWYG).
The former is the preferred mechanism for tools that author HTML, since the structure in the source information can be used to make informed choices regarding which HTML elements and attributes are most appropriate.
However, WYSIWYG tools are legitimate. WYSIWYG tools should use
elements they know are appropriate, and should not use elements
that they do not know to be appropriate. This might in certain
extreme cases mean limiting the use of flow elements to just a few
elements, like div
, b
, i
,
and span
and making liberal use of the style
attribute.
All authoring tools, whether WYSIWYG or not, should make a best effort attempt at enabling users to create well-structured, semantically rich, media-independent content.
Some conformance requirements are phrased as requirements on elements, attributes, methods or objects. Such requirements fall into two categories: those describing content model restrictions, and those describing implementation behavior. The former category of requirements are requirements on documents and authoring tools. The second category are requirements on user agents.
Conformance requirements phrased as algorithms or specific steps may be implemented in any manner, so long as the end result is equivalent. (In particular, the algorithms defined in this specification are intended to be easy to follow, and not intended to be performant.)
User agents may impose implementation-specific limits on otherwise unconstrained inputs, e.g. to prevent denial of service attacks, to guard against running out of memory, or to work around platform-specific limitations.
For compatibility with existing content and prior specifications, this specification describes two authoring formats: one based on XML (referred to as XHTML5), and one using a custom format inspired by SGML (referred to as HTML5). Implementations may support only one of these two formats, although supporting both is encouraged.
The language in this specification assumes that the user agent expands all entity references, and therefore does not include entity reference nodes in the DOM. If user agents do include entity reference nodes in the DOM, then user agents must handle them as if they were fully expanded when implementing this specification. For example, if a requirement talks about an element's child text nodes, then any text nodes that are children of an entity reference that is a child of that element would be used as well. Entity references to unknown entities must be treated as if they contained just an empty text node for the purposes of the algorithms defined in this specification.
This specification relies on several other underlying specifications.
Implementations that support XHTML5 must support some version of XML, as well as its corresponding namespaces specification, because XHTML5 uses an XML serialization with namespaces. [XML] [XMLNAMES]
The Document Object Model (DOM) is a representation — a model — of a document and its content. The DOM is not just an API; the conformance criteria of HTML implementations are defined, in this specification, in terms of operations on the DOM. [DOM3CORE]
Implementations must support some version of DOM Core and DOM Events, because this specification is defined in terms of the DOM, and some of the features are defined as extensions to the DOM Core interfaces. [DOM3CORE] [DOM3EVENTS]
The IDL fragments in this specification must be interpreted as required for conforming IDL fragments, as described in the Web IDL specification. [WebIDL]
Implementations must support some version of the Media Queries language. [MQ]
This specification does not require support of any particular network transport protocols, style sheet language, scripting language, or any of the DOM and WebAPI specifications beyond those described above. However, the language described by this specification is biased towards CSS as the styling language, ECMAScript as the scripting language, and HTTP as the network protocol, and several features assume that those languages and protocols are in use.
This specification might have certain additional requirements on character encodings, image formats, audio formats, and video formats in the respective sections.
this section will be removed at some point
Some elements are defined in terms of their DOM
textContent
attribute. This is an attribute
defined on the Node
interface in DOM3 Core. [DOM3CORE]
The interface DOMTimeStamp
is defined in
DOM3 Core. [DOM3CORE]
The rules for handling alternative style sheets are defined in the CSS object model specification. [CSSOM]
This section will eventually be removed in favour of WebIDL.
A lot of arrays/lists/collections in this spec assume zero-based indexes but use the term "indexth" liberally. We should define those to be zero-based and be clearer about this.
Unless otherwise specified, if a DOM attribute that is a floating
point number type (float
) is assigned an
Infinity or Not-a-Number value, a NOT_SUPPORTED_ERR
exception must be
raised.
Unless otherwise specified, if a method with an argument that is a
floating point number type (float
) is passed
an Infinity or Not-a-Number value, a NOT_SUPPORTED_ERR
exception must be
raised.
Unless otherwise specified, if a method is passed fewer
arguments than is defined for that method in its IDL definition,
a NOT_SUPPORTED_ERR
exception must be
raised.
Unless otherwise specified, if a method is passed more arguments than is defined for that method in its IDL definition, the excess arguments must be ignored.
This specification defines several comparison operators for strings.
Comparing two strings in a case-sensitive manner means comparing them exactly, codepoint for codepoint.
Comparing two strings in an ASCII case-insensitive manner means comparing them exactly, codepoint for codepoint, except that the characters in the range U+0041 .. U+005A (i.e. LATIN CAPITAL LETTER A to LATIN CAPITAL LETTER Z) and the corresponding characters in the range U+0061 .. U+007A (i.e. LATIN SMALL LETTER A to LATIN SMALL LETTER Z) are considered to also match.
Comparing two strings in a compatibility caseless manner means using the Unicode compatibility caseless match operation to compare the two strings. [UNICODECASE]
Converting a string to uppercase means replacing all characters in the range U+0061 .. U+007A (i.e. LATIN SMALL LETTER A to LATIN SMALL LETTER Z) with the corresponding characters in the range U+0041 .. U+005A (i.e. LATIN CAPITAL LETTER A to LATIN CAPITAL LETTER Z).
Converting a string to lowercase means replacing all characters in the range U+0041 .. U+005A (i.e. LATIN CAPITAL LETTER A to LATIN CAPITAL LETTER Z) with the corresponding characters in the range U+0061 .. U+007A (i.e. LATIN SMALL LETTER A to LATIN SMALL LETTER Z).
A string pattern is a prefix match for a string s when pattern is not longer than s and truncating s to pattern's length leaves the two strings as matches of each other.
There are various places in HTML that accept particular data types, such as dates or numbers. This section describes what the conformance criteria for content in those formats is, and how to parse them.
Need to go through the whole spec and make sure all the attribute values are clearly defined either in terms of microsyntaxes or in terms of other specs, or as "Text" or some such.
The space characters, for the purposes of this specification, are U+0020 SPACE, U+0009 CHARACTER TABULATION (tab), U+000A LINE FEED (LF), U+000C FORM FEED (FF), and U+000D CARRIAGE RETURN (CR).
The White_Space characters are those that have the Unicode property "White_Space". [UNICODE]
Some of the micro-parsers described below follow the pattern of having an input variable that holds the string being parsed, and having a position variable pointing at the next character to parse in input.
For parsers based on this pattern, a step that requires the user agent to collect a sequence of characters means that the following algorithm must be run, with characters being the set of characters that can be collected:
Let input and position be the same variables as those of the same name in the algorithm that invoked these steps.
Let result be the empty string.
While position doesn't point past the end of input and the character at position is one of the characters, append that character to the end of result and advance position to the next character in input.
Return result.
The step skip whitespace means that the user agent must collect a sequence of characters that are space characters. The step skip White_Space characters means that the user agent must collect a sequence of characters that are White_Space characters. In both cases, the collected characters are not used. [UNICODE]
When a user agent is to strip line breaks from a string, the user agent must remove any U+000A LINE FEED (LF) and U+000D CARRIAGE RETURN (CR) characters from that string.
The codepoint length of a string is the number of Unicode codepoints in that string.
A number of attributes in HTML5 are boolean attributes. The presence of a boolean attribute on an element represents the true value, and the absence of the attribute represents the false value.
If the attribute is present, its value must either be the empty string or a value that is an ASCII case-insensitive match for the attribute's canonical name, with no leading or trailing whitespace.
The values "true" and "false" are not allowed on boolean attributes. To represent a false value, the attribute has to be omitted altogether.
A string is a valid non-negative integer if it consists of one of more characters in the range U+0030 DIGIT ZERO (0) to U+0039 DIGIT NINE (9).
A valid non-negative integer represents the number that is represented in base ten by that string of digits.
The rules for parsing non-negative integers are as given in the following algorithm. When invoked, the steps must be followed in the order given, aborting at the first step that returns a value. This algorithm will either return zero, a positive integer, or an error. Leading spaces are ignored. Trailing spaces and indeed any trailing garbage characters are ignored.
Let input be the string being parsed.
Let position be a pointer into input, initially pointing at the start of the string.
Let value have the value 0.
If position is past the end of input, return an error.
If the next character is a U+002B PLUS SIGN character (+), advance position to the next character.
If position is past the end of input, return an error.
If the next character is not one of U+0030 DIGIT ZERO (0) .. U+0039 DIGIT NINE (9), then return an error.
If the next character is one of U+0030 DIGIT ZERO (0) .. U+0039 DIGIT NINE (9):
Return value.
A string is a valid integer if it consists of one of more characters in the range U+0030 DIGIT ZERO (0) to U+0039 DIGIT NINE (9), optionally prefixed with a U+002D HYPHEN-MINUS ("-") character.
A valid integer without a U+002D HYPHEN-MINUS ("-") prefix represents the number that is represented in base ten by that string of digits. A valid integer with a U+002D HYPHEN-MINUS ("-") prefix represents the number represented in base ten by the string of digits that follows the U+002D HYPHEN-MINUS, subtracted from zero.
The rules for parsing integers are similar to the rules for non-negative integers, and are as given in the following algorithm. When invoked, the steps must be followed in the order given, aborting at the first step that returns a value. This algorithm will either return an integer or an error. Leading spaces are ignored. Trailing spaces and trailing garbage characters are ignored.
Let input be the string being parsed.
Let position be a pointer into input, initially pointing at the start of the string.
Let value have the value 0.
Let sign have the value "positive".
If position is past the end of input, return an error.
If the character indicated by position (the first character) is a U+002D HYPHEN-MINUS ("-") character:
If the next character is not one of U+0030 DIGIT ZERO (0) .. U+0039 DIGIT NINE (9), then return an error.
If the next character is one of U+0030 DIGIT ZERO (0) .. U+0039 DIGIT NINE (9):
If sign is "positive", return value, otherwise return 0-value.
A string is a valid floating point number if it consists of:
A valid floating point number represents the number obtained by multiplying the significand by ten raised to the power of the exponent, where the significand is the first number, interpreted as base ten (including the decimal point and the number after the decimal point, if any, and interpreting the significand as a negative number if the whole string starts with a U+002D HYPHEN-MINUS ("-") character and the number is not zero), and where the exponent is the number after the E, if any (interpreted as a negative number if there is a U+002D HYPHEN-MINUS ("-") character between the E and the number and the number is not zero, or else ignoring a U+002B PLUS SIGN ("+") character between the E and the number if there is one). If there is no E, then the exponent is treated as zero.
The values ±Infinity and NaN are not valid floating point numbers.
The best representation of the floating point number n is the string obtained from applying the ECMAScript operator ToString to n.
The rules for parsing floating point number values are as given in the following algorithm. As with the previous algorithms, when this one is invoked, the steps must be followed in the order given, aborting at the first step that returns something. This algorithm will either return a number or an error. Leading spaces are ignored. Trailing spaces and garbage characters are ignored.
Let input be the string being parsed.
Let position be a pointer into input, initially pointing at the start of the string.
Let value have the value 1.
Let divisor have the value 1.
Let exponent have the value 1.
If position is past the end of input, return an error.
If the character indicated by position is a U+002D HYPHEN-MINUS ("-") character:
If the character indicated by position is not one of U+0030 DIGIT ZERO (0) .. U+0039 DIGIT NINE (9), then return an error.
Collect a sequence of characters in the range U+0030 DIGIT ZERO (0) to U+0039 DIGIT NINE (9), and interpret the resulting sequence as a base-ten integer. Multiply value by that integer.
If the character indicated by position is a U+002E FULL STOP ("."), run these substeps:
Advance position to the next character.
If position is past the end of input, or if the character indicated by position is not one of U+0030 DIGIT ZERO (0) .. U+0039 DIGIT NINE (9), then return value.
Fraction loop: Multiply divisor by ten.
Advance position to the next character.
If position is past the end of input, then return value.
If the character indicated by position is one of U+0030 DIGIT ZERO (0) .. U+0039 DIGIT NINE (9), return to the step labeled fraction loop in these substeps.
If the character indicated by position is a U+0065 LATIN SMALL LETTER E character or a U+0045 LATIN CAPITAL LETTER E character, run these substeps:
Advance position to the next character.
If position is past the end of input, then return value.
If the character indicated by position is a U+002D HYPHEN-MINUS ("-") character:
If position is past the end of input, then return value.
Otherwise, if the character indicated by position is a U+002B PLUS SIGN ("+") character:
If position is past the end of input, then return value.
If the character indicated by position is not one of U+0030 DIGIT ZERO (0) .. U+0039 DIGIT NINE (9), then return value.
Collect a sequence of characters in the range U+0030 DIGIT ZERO (0) to U+0039 DIGIT NINE (9), and interpret the resulting sequence as a base-ten integer. Multiply exponent by that integer.
Multiply value by ten raised to the exponentth power.
Return value.
The algorithms described in this section are used by
the progress
and meter
elements.
A valid denominator punctuation character is one of the characters from the table below. There is a value associated with each denominator punctuation character, as shown in the table below.
Denominator Punctuation Character | Value | |
---|---|---|
U+0025 PERCENT SIGN | % | 100 |
U+066A ARABIC PERCENT SIGN | ٪ | 100 |
U+FE6A SMALL PERCENT SIGN | ﹪ | 100 |
U+FF05 FULLWIDTH PERCENT SIGN | % | 100 |
U+2030 PER MILLE SIGN | ‰ | 1000 |
U+2031 PER TEN THOUSAND SIGN | ‱ | 10000 |
The steps for finding one or two numbers of a ratio in a string are as follows:
The algorithm to find a number is as follows. It is given a string and a starting position, and returns either nothing, a number, or an error condition.
The rules for parsing dimension values are as given in the following algorithm. When invoked, the steps must be followed in the order given, aborting at the first step that returns a value. This algorithm will either return a number greater than or equal to 1.0, or an error; if a number is returned, then it is further categorised as either a percentage or a length.
Let input be the string being parsed.
Let position be a pointer into input, initially pointing at the start of the string.
If position is past the end of input, return an error.
If the next character is a U+002B PLUS SIGN character (+), advance position to the next character.
Collect a sequence of characters that are U+0030 DIGIT ZERO (0) characters, and discard them.
If position is past the end of input, return an error.
If the next character is not one of U+0031 DIGIT ONE (1) .. U+0039 DIGIT NINE (9), then return an error.
Collect a sequence of characters in the range U+0030 DIGIT ZERO (0) to U+0039 DIGIT NINE (9), and interpret the resulting sequence as a base-ten integer. Let value be that number.
If position is past the end of input, return value as an integer.
If the next character is a U+002E FULL STOP character (.):
Advance position to the next character.
If the next character is not one of U+0030 DIGIT ZERO (0) .. U+0039 DIGIT NINE (9), then return value as an integer.
Collect a sequence of characters in the range U+0030 DIGIT ZERO (0) to U+0039 DIGIT NINE (9). Let length be the number of characters collected. Let fraction be the result of interpreting the collected characters as a base-ten integer, and then dividing that number by 10length.
Increment value by fraction.
If position is past the end of input, return value as a length.
If the next character is a U+0025 PERCENT SIGN character (%), return value as a percentage.
Return value as a length.
A valid list of integers is a number of valid integers separated by U+002C COMMA characters, with no other characters (e.g. no space characters). In addition, there might be restrictions on the number of integers that can be given, or on the range of values allowed.
The rules for parsing a list of integers are as follows:
Let input be the string being parsed.
Let position be a pointer into input, initially pointing at the start of the string.
Let numbers be an initially empty list of integers. This list will be the result of this algorithm.
If there is a character in the string input at position position, and it is either a U+0020 SPACE, U+002C COMMA, or U+003B SEMICOLON character, then advance position to the next character in input, or to beyond the end of the string if there are no more characters.
If position points to beyond the end of input, return numbers and abort.
If the character in the string input at position position is a U+0020 SPACE, U+002C COMMA, or U+003B SEMICOLON character, then return to step 4.
Let negated be false.
Let value be 0.
Let started be false. This variable is
set to true when the parser sees a number or a "-
" character.
Let got number be false. This variable is set to true when the parser sees a number.
Let finished be false. This variable is set to true to switch parser into a mode where it ignores characters until the next separator.
Let bogus be false.
Parser: If the character in the string input at position position is:
Follow these substeps:
Follow these substeps:
Follow these substeps:
1,2,x,4
".Follow these substeps:
Follow these substeps:
Advance position to the next character in input, or to beyond the end of the string if there are no more characters.
If position points to a character (and not to beyond the end of input), jump to the big Parser step above.
If negated is true, then negate value.
If got number is true, then append value to the numbers list.
Return the numbers list and abort.
The rules for parsing a list of dimensions are as follows. These rules return a list of zero or more pairs consisting of a number and a unit, the unit being one of percentage, relative, and absolute.
Let raw input be the string being parsed.
If the last character in raw input is a U+002C COMMA character (","), then remove that character from raw input.
Split the string raw input on commas. Let raw tokens be the resulting list of tokens.
Let result be an empty list of number/unit pairs.
For each token in raw tokens, run the following substeps:
Let input be the token.
Let position be a pointer into input, initially pointing at the start of the string.
Let value be the number 0.
Let unit be absolute.
If position is past the end of input, set unit to relative and jump to the last substep.
If the character at position is a character in the range U+0030 DIGIT ZERO (0) to U+0039 DIGIT NINE (9), collect a sequence of characters in the range U+0030 DIGIT ZERO (0) to U+0039 DIGIT NINE (9), interpret the resulting sequence as an integer in base ten, and increment value by that integer.
If the character at position is a U+002E FULL STOP character (.), run these substeps:
Collect a sequence of characters consisting of space characters and characters in the range U+0030 DIGIT ZERO (0) to U+0039 DIGIT NINE (9). Let s be the resulting sequence.
Remove all space characters in s.
If s is not the empty string, run these subsubsteps:
Let length be the number of characters in s (after the spaces were removed).
Let fraction be the result of interpreting s as a base-ten integer, and then dividing that number by 10length.
Increment value by fraction.
If the character at position is a U+0025 PERCENT SIGN (%) character, then set unit to percentage.
Otherwise, if the character at position is a U+002A ASTERISK character (*), then set unit to relative.
Add an entry to result consisting of the number given by value and the unit given by unit.
Return the list result.
In the algorithms below, the number of days in month month of year year is: 31 if month is 1, 3, 5, 7, 8, 10, or 12; 30 if month is 4, 6, 9, or 11; 29 if month is 2 and year is a number divisible by 400, or if year is a number divisible by 4 but not by 100; and 28 otherwise. This takes into account leap years in the Gregorian calendar. [GREGORIAN]
The digits in the date and time syntaxes defined in this section must be characters in the range U+0030 DIGIT ZERO to U+0039 DIGIT NINE, used to express numbers in base ten.
A month consists of a specific proleptic Gregorian date with no timezone information and no date information beyond a year and a month. [GREGORIAN]
A string is a valid month string representing a year year and month month if it consists of the following components in the given order:
The rules to parse a month string are as follows. This will either return a year and month, or nothing. If at any point the algorithm says that it "fails", this means that it is aborted at that point and returns nothing.
Let input be the string being parsed.
Let position be a pointer into input, initially pointing at the start of the string.
Parse a month component to obtain year and month. If this returns nothing, then fail.
If position is not beyond the end of input, then fail.
Return year and month.
The rules to parse a month component, given an input string and a position, are as follows. This will either return a year and a month, or nothing. If at any point the algorithm says that it "fails", this means that it is aborted at that point and returns nothing.
Collect a sequence of characters in the range U+0030 DIGIT ZERO (0) to U+0039 DIGIT NINE (9). If the collected sequence is not at least four characters long, then fail. Otherwise, interpret the resulting sequence as a base-ten integer. Let that number be the year.
If year is not a number greater than zero, then fail.
If position is beyond the end of input or if the character at position is not a U+002D HYPHEN-MINUS character, then fail. Otherwise, move position forwards one character.
Collect a sequence of characters in the range U+0030 DIGIT ZERO (0) to U+0039 DIGIT NINE (9). If the collected sequence is not exactly two characters long, then fail. Otherwise, interpret the resulting sequence as a base-ten integer. Let that number be the month.
If month is not a number in the range 1 ≤ month ≤ 12, then fail.
Return year and month.
A date consists of a specific proleptic Gregorian date with no timezone information, consisting of a year, a month, and a day. [GREGORIAN]
A string is a valid date string representing a year year, month month, and day day if it consists of the following components in the given order:
The rules to parse a date string are as follows. This will either return a date, or nothing. If at any point the algorithm says that it "fails", this means that it is aborted at that point and returns nothing.
Let input be the string being parsed.
Let position be a pointer into input, initially pointing at the start of the string.
Parse a date component to obtain year, month, and day. If this returns nothing, then fail.
If position is not beyond the end of input, then fail.
Let date be the date with year year, month month, and day day.
Return date.
The rules to parse a date component, given an input string and a position, are as follows. This will either return a year, a month, and a day, or nothing. If at any point the algorithm says that it "fails", this means that it is aborted at that point and returns nothing.
Parse a month component to obtain year and month. If this returns nothing, then fail.
Let maxday be the number of days in month month of year year.
If position is beyond the end of input or if the character at position is not a U+002D HYPHEN-MINUS character, then fail. Otherwise, move position forwards one character.
Collect a sequence of characters in the range U+0030 DIGIT ZERO (0) to U+0039 DIGIT NINE (9). If the collected sequence is not exactly two characters long, then fail. Otherwise, interpret the resulting sequence as a base-ten integer. Let that number be the day.
If day is not a number in the range 1 ≤ month ≤ maxday, then fail.
Return year, month, and day.
A time consists of a specific time with no timezone information, consisting of an hour, a minute, a second, and a fraction of a second.
A string is a valid time string representing an hour hour, a minute minute, and a second second if it consists of the following components in the given order:
The second component cannot be 60 or 61; leap seconds cannot be represented.
The rules to parse a time string are as follows. This will either return a time, or nothing. If at any point the algorithm says that it "fails", this means that it is aborted at that point and returns nothing.
Let input be the string being parsed.
Let position be a pointer into input, initially pointing at the start of the string.
Parse a time component to obtain hour, minute, and second. If this returns nothing, then fail.
If position is not beyond the end of input, then fail.
Let time be the time with hour hour, minute minute, and second second.
Return time.
The rules to parse a time component, given an input string and a position, are as follows. This will either return an hour, a minute, and a second, or nothing. If at any point the algorithm says that it "fails", this means that it is aborted at that point and returns nothing.
Collect a sequence of characters in the range U+0030 DIGIT ZERO (0) to U+0039 DIGIT NINE (9). If the collected sequence is not exactly two characters long, then fail. Otherwise, interpret the resulting sequence as a base-ten integer. Let that number be the hour.
If position is beyond the end of input or if the character at position is not a U+003A COLON character, then fail. Otherwise, move position forwards one character.
Collect a sequence of characters in the range U+0030 DIGIT ZERO (0) to U+0039 DIGIT NINE (9). If the collected sequence is not exactly two characters long, then fail. Otherwise, interpret the resulting sequence as a base-ten integer. Let that number be the minute.
Let second be a string with the value "0".
If position is not beyond the end of input and the character at position is a U+003A COLON, then run these substeps:
Advance position to the next character in input.
If position is beyond the end of input, or at the last character in input, or if the next two characters in input starting at position are not two characters both in the range U+0030 DIGIT ZERO (0) to U+0039 DIGIT NINE (9), then fail.
Collect a sequence of characters that are either characters in the range U+0030 DIGIT ZERO (0) to U+0039 DIGIT NINE (9) or U+002E FULL STOP characters. If the collected sequence has more than one U+002E FULL STOP characters, or if the last character in the sequence is a U+002E FULL STOP character, then fail. Otherwise, let the collected string be second instead of its previous value.
Interpret second as a base-ten number (possibly with a fractional part). Let second be that number instead of the string version.
If second is not a number in the range 0 ≤ second < 60, then fail.
Return hour, minute, and second.
A local date and time consists of a specific proleptic Gregorian date, consisting of a year, a month, and a day, and a time, consisting of an hour, a minute, a second, and a fraction of a second, but expressed without a time zone. [GREGORIAN]
A string is a valid local date and time string representing a date and time if it consists of the following components in the given order:
The rules to parse a local date and time string are as follows. This will either return a date and time, or nothing. If at any point the algorithm says that it "fails", this means that it is aborted at that point and returns nothing.
Let input be the string being parsed.
Let position be a pointer into input, initially pointing at the start of the string.
Parse a date component to obtain year, month, and day. If this returns nothing, then fail.
If position is beyond the end of input or if the character at position is not a U+0054 LATIN CAPITAL LETTER T character then fail. Otherwise, move position forwards one character.
Parse a time component to obtain hour, minute, and second. If this returns nothing, then fail.
If position is not beyond the end of input, then fail.
Let date be the date with year year, month month, and day day.
Let time be the time with hour hour, minute minute, and second second.
Return date and time.
A global date and time consists of a specific proleptic Gregorian date, consisting of a year, a month, and a day, and a time, consisting of an hour, a minute, a second, and a fraction of a second, expressed with a time zone, consisting of a number of hours and minutes. [GREGORIAN]
A string is a valid global date and time string representing a date, time, and a timezone offset if it consists of the following components in the given order:
This format allows for time zone offsets from -23:59 to +23:59. In practice, however, the range of actual time zones is -12:00 to +14:00, and the minutes component of actual time zones is always either 00, 30, or 45.
The following are some examples of dates written as valid global date and time strings.
0037-12-13T00:00Z
"1979-10-14T12:00:00.001-04:00
"8592-01-01T02:09+02:09
"Several things are notable about these dates:
The rules to parse a global date and time string are as follows. This will either return a time in UTC, with associated timezone information for round tripping or display purposes, or nothing. If at any point the algorithm says that it "fails", this means that it is aborted at that point and returns nothing.
Let input be the string being parsed.
Let position be a pointer into input, initially pointing at the start of the string.
Parse a date component to obtain year, month, and day. If this returns nothing, then fail.
If position is beyond the end of input or if the character at position is not a U+0054 LATIN CAPITAL LETTER T character then fail. Otherwise, move position forwards one character.
Parse a time component to obtain hour, minute, and second. If this returns nothing, then fail.
If position is beyond the end of input, then fail.
Parse a timezone component to obtain timezonehours and timezoneminutes. If this returns nothing, then fail.
If position is not beyond the end of input, then fail.
Let time be the moment in time at year year, month month, day day, hours hour, minute minute, second second, subtracting timezonehours hours and timezoneminutes minutes. That moment in time is a moment in the UTC timezone.
Let timezone be timezonehours hours and timezoneminutes minutes from UTC.
Return time and timezone.
The rules to parse a timezone component, given an input string and a position, are as follows. This will either return timezone hours and timezone minutes, or nothing. If at any point the algorithm says that it "fails", this means that it is aborted at that point and returns nothing.
If the character at position is a U+005A LATIN CAPITAL LETTER Z, then:
Let timezonehours be 0.
Let timezoneminutes be 0.
Advance position to the next character in input.
Otherwise, if the character at position is either a U+002B PLUS SIGN ("+") or a U+002D HYPHEN-MINUS ("-"), then:
If the character at position is a U+002B PLUS SIGN ("+"), let sign be "positive". Otherwise, it's a U+002D HYPHEN-MINUS ("-"); let sign be "negative".
Advance position to the next character in input.
Collect a sequence of characters in the range U+0030 DIGIT ZERO (0) to U+0039 DIGIT NINE (9). If the collected sequence is not exactly two characters long, then fail. Otherwise, interpret the resulting sequence as a base-ten integer. Let that number be the timezonehours.
If position is beyond the end of input or if the character at position is not a U+003A COLON character, then fail. Otherwise, move position forwards one character.
Collect a sequence of characters in the range U+0030 DIGIT ZERO (0) to U+0039 DIGIT NINE (9). If the collected sequence is not exactly two characters long, then fail. Otherwise, interpret the resulting sequence as a base-ten integer. Let that number be the timezoneminutes.
Return timezonehours and timezoneminutes.
A week consists of a week-year number and a week number representing a seven day period. Each week-year in this calendaring system has either 52 weeks or 53 weeks, as defined below. A week is a seven-day period. The week starting on the Gregorian date Monday December 29th 1969 (1969-12-29) is defined as week number 1 in week-year 1970. Consecutive weeks are numbered sequentially. The week before the number 1 week in a week-year is the last week in the previous week-year, and vice versa. [GREGORIAN]
A week-year with a number year that corresponds to a year year in the proleptic Gregorian calendar that has a Thursday as its first day (January 1st), and a week-year year where year is a number divisible by 400, or a number divisible by 4 but not by 100, has 53 weeks. All other week-years have 52 weeks.
The week number of the last day of a week-year with 53 weeks is 53; the week number of the last day of a week-year with 52 weeks is 52.
The week-year number of a particular day can be different than the number of the year that contains that day in the proleptic Gregorian calendar. The first week in a week-year year is the week that contains the first Thursday of the Gregorian year year.
A string is a valid week string representing a week-year year and week week if it consists of the following components in the given order:
The rules to parse a week string are as follows. This will either return a week-year number and week number, or nothing. If at any point the algorithm says that it "fails", this means that it is aborted at that point and returns nothing.
Let input be the string being parsed.
Let position be a pointer into input, initially pointing at the start of the string.
Collect a sequence of characters in the range U+0030 DIGIT ZERO (0) to U+0039 DIGIT NINE (9). If the collected sequence is not at least four characters long, then fail. Otherwise, interpret the resulting sequence as a base-ten integer. Let that number be the year.
If year is not a number greater than zero, then fail.
If position is beyond the end of input or if the character at position is not a U+002D HYPHEN-MINUS character, then fail. Otherwise, move position forwards one character.
If position is beyond the end of input or if the character at position is not a U+0057 LATIN CAPITAL LETTER W character, then fail. Otherwise, move position forwards one character.
Collect a sequence of characters in the range U+0030 DIGIT ZERO (0) to U+0039 DIGIT NINE (9). If the collected sequence is not exactly two characters long, then fail. Otherwise, interpret the resulting sequence as a base-ten integer. Let that number be the week.
Let maxweek be the week number of the last day of year year.
If week is not a number in the range 1 ≤ week ≤ maxweek, then fail.
If position is not beyond the end of input, then fail.
Return the week-year number year and the week number week.
A date or time string consists of either a date, a time, or a global date and time.
A string is a valid date or time string if it is also one of the following:
A string is a valid date or time string in content if it consists of zero or more White_Space characters, followed by a valid date or time string, followed by zero or more further White_Space characters.
The rules to parse a date or time string are as follows. The algorithm is invoked with a flag indicating if the in attribute variant or the in content variant is to be used. The algorithm will either return a date, a time, a global date and time, or nothing. If at any point the algorithm says that it "fails", this means that it is aborted at that point and returns nothing.
Let input be the string being parsed.
Let position be a pointer into input, initially pointing at the start of the string.
For the in content variant: skip White_Space characters.
Set start position to the same position as position.
Set the date present and time present flags to true.
Parse a date component to obtain year, month, and day. If this fails, then set the date present flag to false.
If date present is true, and position is not beyond the end of input, and the character at position is a U+0054 LATIN CAPITAL LETTER T character, then advance position to the next character in input.
Otherwise, if date present is true, and either position is beyond the end of input or the character at position is not a U+0054 LATIN CAPITAL LETTER T character, then set time present to false.
Otherwise, if date present is false, set position back to the same position as start position.
If the time present flag is true, then parse a time component to obtain hour, minute, and second. If this returns nothing, then set the time present flag to false.
If both the date present and time present flags are false, then fail.
If the time present flag is true, but position is beyond the end of input, then fail.
If the date present and time present flags are both true, parse a timezone component to obtain timezonehours and timezoneminutes. If this returns nothing, then fail.
For the in content variant: skip White_Space characters.
If position is not beyond the end of input, then fail.
If the date present flag is true and the time present flag is false, then let date be the date with year year, month month, and day day, and return date.
Otherwise, if the time present flag is true and the date present flag is false, then let time be the time with hour hour, minute minute, and second second, and return time.
Otherwise, let time be the moment in time at year year, month month, day day, hours hour, minute minute, second second, subtracting timezonehours hours and timezoneminutes minutes, that moment in time being a moment in the UTC timezone; let timezone be timezonehours hours and timezoneminutes minutes from UTC; and return time and timezone.
A simple color consists of three 8-bit numbers in the range 0..255, representing the red, green, and blue components of the color respectively, in the sRGB color space. [SRGB]
A string is a valid simple color if it is exactly seven characters long, and the first character is a U+0023 NUMBER SIGN (#) character, and the remaining six characters are all in the range U+0030 DIGIT ZERO (0) .. U+0039 DIGIT NINE (9), U+0041 LATIN CAPITAL LETTER A .. U+0046 LATIN CAPITAL LETTER F, U+0061 LATIN SMALL LETTER A .. U+0066 LATIN SMALL LETTER F, with the first two digits representing the red component, the middle two digits representing the green component, and the last two digits representing the blue component, in hexadecimal.
A string is a valid lowercase simple color if it is a valid simple color and doesn't use any characters in the range U+0041 LATIN CAPITAL LETTER A .. U+0046 LATIN CAPITAL LETTER F.
The rules for parsing simple color values are as given in the following algorithm. When invoked, the steps must be followed in the order given, aborting at the first step that returns a value. This algorithm will either return a simple color or an error.
Let input be the string being parsed.
If input is not exactly seven characters long, then return an error.
If the first character in input is not a U+0023 NUMBER SIGN (#) character, then return an error.
If the last six characters of input are not all in the range U+0030 DIGIT ZERO (0) .. U+0039 DIGIT NINE (9), U+0041 LATIN CAPITAL LETTER A .. U+0046 LATIN CAPITAL LETTER F, U+0061 LATIN SMALL LETTER A .. U+0066 LATIN SMALL LETTER F, then return an error.
Let result be a simple color.
Interpret the second and third characters as a hexadecimal number and let the result be the red component of result.
Interpret the fourth and fifth characters as a hexadecimal number and let the result be the green component of result.
Interpret the sixth and seventh characters as a hexadecimal number and let the result be the blue component of result.
Return result.
The rules for serialising simple color values given a simple color are as given in the following algorithm:
Let result be a string consisting of a single U+0023 NUMBER SIGN (#) character.
Convert the red, green, and blue components in turn to two-digit hexadecimal numbers using the digits U+0030 DIGIT ZERO (0) .. U+0039 DIGIT NINE (9) and U+0061 LATIN SMALL LETTER A .. U+0066 LATIN SMALL LETTER F, zero-padding if necessary, and append these numbers to result, in the order red, green, blue.
Return result, which will be a valid lowercase simple color.
Some obsolete legacy attributes parse colors in a more complicated manner, using the rules for parsing a legacy color value, which are given in the following algorithm. When invoked, the steps must be followed in the order given, aborting at the first step that returns a value. This algorithm will either return a simple color or an error.
Let input be the string being parsed.
If input is the empty string, then return an error.
If input is an ASCII case-insensitive match for one of the keywords listed in the SVG color keywords section of the CSS3 Color specification, the return the simple color corresponding to that keyword. [CSS3COLOR]
If input is four characters long, and the first character in input is a U+0023 NUMBER SIGN (#) character, and the the last three characters of input are all in the range U+0030 DIGIT ZERO (0) .. U+0039 DIGIT NINE (9), U+0041 LATIN CAPITAL LETTER A .. U+0046 LATIN CAPITAL LETTER F, and U+0061 LATIN SMALL LETTER A .. U+0066 LATIN SMALL LETTER F, then run these substeps:
Let result be a simple color.
Interpret the second character of input as a hexadecimal digit; let the red component of result be the resulting number multiplied by 17.
Interpret the third character of input as a hexadecimal digit; let the green component of result be the resulting number multiplied by 17.
Interpret the fourth character of input as a hexadecimal digit; let the blue component of result be the resulting number multiplied by 17.
Return result.
Replace any characters in input that
have a Unicode codepoint greater than U+FFFF (i.e. any characters
that are not in the basic multilingual plane) with the
two-character string "00
".
If input is longer than 128 characters, truncate input, leaving only the first 128 characters.
If the first character in input is a U+0023 NUMBER SIGN character (#), remove it.
Replace any character in input that is not in the range U+0030 DIGIT ZERO (0) .. U+0039 DIGIT NINE (9), U+0041 LATIN CAPITAL LETTER A .. U+0046 LATIN CAPITAL LETTER F, and U+0061 LATIN SMALL LETTER A .. U+0066 LATIN SMALL LETTER F with the character U+0030 DIGIT ZERO (0).
While input's length is zero or not a multiple of three, append a U+0030 DIGIT ZERO (0) character to input.
Split input into three strings of equal length, to obtain three components. Let length be the length of those components (one third the length of input).
If length is greater than 8, then remove the leading length-8 characters in each component, and let length be 8.
While length is greater than two and the first character in each component is a U+0030 DIGIT ZERO (0) character, remove that character and reduce length by one.
If length is still greater than two, truncate each component, leaving only the first two characters in each.
Let result be a simple color.
Interpret the first component as a hexadecimal number; let the red component of result be the resulting number.
Interpret the second component as a hexadecimal number; let the green component of result be the resulting number.
Interpret the third component as a hexadecimal number; let the blue component of result be the resulting number.
Return result.
The 2D graphics context has a separate color syntax that also handles opacity.
A set of space-separated tokens is a set of zero or more words separated by one or more space characters, where words consist of any string of one or more characters, none of which are space characters.
A string containing a set of space-separated tokens may have leading or trailing space characters.
An unordered set of unique space-separated tokens is a set of space-separated tokens where none of the words are duplicated.
An ordered set of unique space-separated tokens is a set of space-separated tokens where none of the words are duplicated but where the order of the tokens is meaningful.
Sets of space-separated tokens sometimes have a defined set of allowed values. When a set of allowed values is defined, the tokens must all be from that list of allowed values; other values are non-conforming. If no such set of allowed values is provided, then all values are conforming.
When a user agent has to split a string on spaces, it must use the following algorithm:
Let input be the string being parsed.
Let position be a pointer into input, initially pointing at the start of the string.
Let tokens be a list of tokens, initially empty.
While position is not past the end of input:
Collect a sequence of characters that are not space characters.
Add the string collected in the previous step to tokens.
Return tokens.
When a user agent has to remove a token from a string, it must use the following algorithm:
Let input be the string being modified.
Let token be the token being removed. It will not contain any space characters.
Let output be the output string, initially empty.
Let position be a pointer into input, initially pointing at the start of the string.
If position is beyond the end of input, set the string being modified to output, and abort these steps.
If the character at position is a space character:
Append the character at position to the end of output.
Increment position so it points at the next character in input.
Return to step 5 in the overall set of steps.
Otherwise, the character at position is the first character of a token. Collect a sequence of characters that are not space characters, and let that be s.
If s is exactly equal to token, then:
Skip whitespace (in input).
Remove any space characters currently at the end of output.
If position is not past the end of input, and output is not the empty string, append a single U+0020 SPACE character at the end of output.
Otherwise, append s to the end of output.
Return to step 6 in the overall set of steps.
This causes any occurrences of the token to be removed from the string, and any spaces that were surrounding the token to be collapsed to a single space, except at the start and end of the string, where such spaces are removed.
A set of comma-separated tokens is a set of zero or
more tokens each separated from the next by a single U+002C COMMA
character (,
), where tokens consist of any
string of zero or more characters, neither beginning nor ending with
space characters, nor
containing any U+002C COMMA characters (,
),
and optionally surrounded by space
characters.
For instance, the string " a ,b,,d d
" consists of four
tokens: "a", "b", the empty string, and "d d". Leading and
trailing whitespace around each token doesn't count as part of the
token, and the empty string can be a token.
Sets of comma-separated tokens sometimes have further restrictions on what consists a valid token. When such restrictions are defined, the tokens must all fit within those restrictions; other values are non-conforming. If no such restrictions are specified, then all values are conforming.
When a user agent has to split a string on commas, it must use the following algorithm:
Let input be the string being parsed.
Let position be a pointer into input, initially pointing at the start of the string.
Let tokens be a list of tokens, initially empty.
Token: If position is past the end of input, jump to the last step.
Collect a sequence of characters that are not
U+002C COMMA characters (,
). Let s be the resulting sequence (which might be the
empty string).
Remove any leading or trailing sequence of space characters from s.
Add s to tokens.
If position is not past the end of input, then the character at position is a U+002C COMMA character (,
); advance position past that
character.
Jump back to the step labeled token.
Return tokens.
Some attributes are defined as taking one of a finite set of keywords. Such attributes are called enumerated attributes. The keywords are each defined to map to a particular state (several keywords might map to the same state, in which case some of the keywords are synonyms of each other; additionally, some of the keywords can be said to be non-conforming, and are only in the specification for historical reasons). In addition, two default states can be given. The first is the invalid value default, the second is the missing value default.
If an enumerated attribute is specified, the attribute's value must be an ASCII case-insensitive match for one of the given keywords that are not said to be non-conforming, with no leading or trailing whitespace.
When the attribute is specified, if its value is an ASCII case-insensitively match for one of the given keywords then that keyword's state is the state that the attribute represents. If the attribute value matches none of the given keywords, but the attribute has an invalid value default, then the attribute represents that state. Otherwise, if the attribute value matches none of the keywords but there is a missing value default state defined, then that is the state represented by the attribute. Otherwise, there is no default, and invalid values must be ignored.
When the attribute is not specified, if there is a missing value default state defined, then that is the state represented by the (missing) attribute. Otherwise, the absence of the attribute means that there is no state represented.
The empty string can be one of the keywords in some
cases. For example the contenteditable
attribute has
two states: true, matching the true
keyword and the empty string, false, matching false
and all other keywords (it's the invalid
value default). It could further be thought of as having a
third state inherit, which would be the default when the
attribute is not specified at all (the missing value
default), but for various reasons that isn't the way this
specification actually defines it.
A valid hash-name reference to an element of type type is a string consisting of a U+0023 NUMBER SIGN
(#
) character followed by a string which
exactly matches the value of the name
attribute of an element in the document with type type.
The rules for parsing a hash-name reference to an element of type type are as follows:
If the string being parsed does not contain a U+0023 NUMBER SIGN character, or if the first such character in the string is the last character in the string, then return null and abort these steps.
Let s be the string from the character immediately after the first U+0023 NUMBER SIGN character in the string being parsed up to the end of that string.
Return the first element of type type
that has an id
attribute whose value
is a case-sensitive match for s or
a name
attribute whose value is a
compatibility caseless match for s.
This specification defines the term URL, and defines various algorithms for dealing with URLs, because for historical reasons the rules defined by the URI and IRI specifications are not a complete description of what HTML user agents need to implement to be compatible with Web content.
A URL is a string used to identify a resource.
A URL is a valid URL if at least one of the following conditions holds:
The URL is a valid IRI reference and it has no query component. [RFC3987]
The URL is a valid IRI reference and its query component contains no unescaped non-ASCII characters. [RFC3987]
The URL is a valid IRI reference and the character encoding of
the URL's Document
is UTF-8 or UTF-16. [RFC3987]
A URL has an associated URL character encoding, determined as follows:
Document
, and the URL character
encoding is the document's character encoding.The term "URL" in this specification is used in a manner distinct from the precise technical meaning it is given in RFC 3986. Readers familiar with that RFC will find it easier to read this specification if they pretend the term "URL" as used herein is really called something else altogether.
To parse a URL url into its component parts, the user agent must use the following steps:
Strip leading and trailing space characters from url.
Parse url in the manner defined by RFC 3986, with the following exceptions:
If url doesn't match the <URI-reference> production, even after the above changes are made to the ABNF definitions, then parsing the URL fails with an error. [RFC3986]
Otherwise, parsing url was successful; the components of the URL are substrings of url defined as follows:
The substring matched by the <scheme> production, if any.
The substring matched by the <host> production, if any.
The substring matched by the <port> production, if any.
If there is a <scheme> component and a <port> component and the port given by the <port> component is different than the default port defined for the protocol given by the <scheme> component, then <hostport> is the substring that starts with the substring matched by the <host> production and ends with the substring matched by the <port> production, and includes the colon in between the two. Otherwise, it is the same as the <host> component.
The substring matched by one of the following productions, if one of them was matched:
The substring matched by the <query> production, if any.
The substring matched by the <fragment> production, if any.
The substring that follows the substring matched by the <authority> production, or the whole string if the <authority> production wasn't matched.
To resolve a URL to an absolute URL relative to either another absolute URL or an element, the user agent must use the following steps. Resolving a URL can result in an error, in which case the URL is not resolvable.
Let url be the URL being resolved.
Let encoding be the URL character encoding.
If encoding is UTF-16, then change it to UTF-8.
If the algorithm was invoked with an absolute URL to use as the base URL, let base be that absolute URL.
Otherwise, let base be the base URI of
the element, as defined by the XML Base specification, with
the base URI of the document entity being defined as the
document base URL of the Document
that
owns the element. [XMLBASE]
For the purposes of the XML Base specification, user agents
must act as if all Document
objects represented XML
documents.
It is possible for xml:base
attributes to be present
even in HTML fragments, as such attributes can be added
dynamically using script. (Such scripts would not be conforming,
however, as xml:base
attributes
are not allowed in HTML documents.)
The document base URL of a Document
is
the absolute URL obtained by running these
substeps:
Let fallback base url be the document's address.
If fallback base url is
about:blank
, and the Document
's
browsing context has a creator browsing
context, then let fallback base url
be the document base URL of the creator
Document
instead.
If there is no base
element that is both a
child of the head
element and has an
href
attribute, then the
document base URL is fallback base
url.
Otherwise, let url be the value of the
href
attribute of the first
such element.
Resolve url relative to fallback base
url (thus, the base
href
attribute isn't affected by
xml:base
attributes).
The document base URL is the result of the previous step if it was successful; otherwise it is fallback base url.
Parse url into its component parts.
If parsing url resulted in a <host> component, then replace the matching subtring of url with the string that results from expanding any sequences of percent-encoded octets in that component that are valid UTF-8 sequences into Unicode characters as defined by UTF-8.
If any percent-encoded octets in that component are not valid UTF-8 sequences, then return an error and abort these steps.
Apply the IDNA ToASCII algorithm to the matching substring, with both the AllowUnassigned and UseSTD3ASCIIRules flags set. Replace the matching substring with the result of the ToASCII algorithm.
If ToASCII fails to convert one of the components of the string, e.g. because it is too long or because it contains invalid characters, then return an error and abort these steps. [RFC3490]
If parsing url resulted in a <path> component, then replace the matching substring of url with the string that results from applying the following steps to each character other than U+0025 PERCENT SIGN (%) that doesn't match the original <path> production defined in RFC 3986:
For instance if url was "//example.com/a^b☺c%FFd%z/?e
", then the
<path> component's substring
would be "/a^b☺c%FFd%z/
" and the two
characters that would have to be escaped would be "^
" and "☺
". The
result after this step was applied would therefore be that url now had the value "//example.com/a%5Eb%E2%98%BAc%FFd%z/?e
".
If parsing url resulted in a <query> component, then replace the matching substring of url with the string that results from applying the following steps to each character other than U+0025 PERCENT SIGN (%) that doesn't match the original <query> production defined in RFC 3986:
Apply the algorithm described in RFC 3986 section 5.2 Relative Resolution, using url as the potentially relative URI reference (R), and base as the base URI (Base). [RFC3986]
Apply any relevant conformance criteria of RFC 3986 and RFC 3987, returning an error and aborting these steps if appropriate. [RFC3986] [RFC3987]
For instance, if an absolute URI that would be
returned by the above algorithm violates the restrictions specific
to its scheme, e.g. a data:
URI using the
"//
" server-based naming authority syntax,
then user agents are to treat this as an error instead.
Let result be the target URI (T) returned by the Relative Resolution algorithm.
If result uses a scheme with a server-based naming authority, replace all U+005C REVERSE SOLIDUS (\) characters in result with U+002F SOLIDUS (/) characters.
Return result.
A URL is an absolute URL if resolving it results in the same URL without an error.
When an xml:base
attribute
changes, the attribute's element, and all descendant elements, are
affected by a base URL change.
When a document's document base URL changes, all elements in that document are affected by a base URL change.
When an element is moved from one document to another, if the two documents have different base URLs, then that element and all its descendants are affected by a base URL change.
When an element is affected by a base URL change, it must act as described in the following list:
If the absolute URL identified by the hyperlink is
being shown to the user, or if any data derived from that URL is
affecting the display, then the href
attribute should be reresolved relative to the element
and the UI updated appropriately.
For example, the CSS :link
/:visited
pseudo-classes might have
been affected.
If the hyperlink has a ping
attribute and its absolute URL(s) are being shown to the
user, then the ping
attribute's tokens should be reresolved relative to the element and the UI updated
appropriately.
blockquote
, q
,
ins
, or del
element with a cite
attributeIf the absolute URL identified by the cite
attribute is being shown to the user, or if
any data derived from that URL is affecting the display, then the
URL should be reresolved relative to the element and the UI updated
appropriately.
The element is not directly affected.
Changing the base URL doesn't affect the image
displayed by img
elements, although subsequent
accesses of the src
DOM attribute
from script will return a new absolute URL that might
no longer correspond to the image being shown.
An interface that has a complement of URL decomposition attributes will have seven attributes with the following definitions:
attribute DOMString protocol; attribute DOMString host; attribute DOMString hostname; attribute DOMString port; attribute DOMString pathname; attribute DOMString search; attribute DOMString hash;
The attributes defined to be URL decomposition attributes must act as described for the attributes with the same corresponding names in this section.
In addition, an interface with a complement of URL decomposition attributes will define an input, which is a URL that the attributes act on, and a common setter action, which is a set of steps invoked when any of the attributes' setters are invoked.
The seven URL decomposition attributes have similar requirements.
On getting, if the input fulfills the condition given in the "getter condition" column corresponding to the attribute in the table below, the user agent must return the part of the input URL given in the "component" column, with any prefixes specified in the "prefix" column appropriately added to the start of the string and any suffixes specified in the "suffix" column appropriately added to the end of the string. Otherwise, the attribute must return the empty string.
On setting, the new value must first be mutated as described by the "setter preprocessor" column, then mutated by %-escaping any characters in the new value that are not valid in the relevant component as given by the "component" column. Then, if the resulting new value fulfills the condition given in the "setter condition" column, the user agent must make a new string output by replacing the component of the URL given by the "component" column in the input URL with the new value; otherwise, the user agent must let output be equal to the input. Finally, the user agent must invoke the common setter action with the value of output.
When replacing a component in the URL, if the component is part of an optional group in the URL syntax consisting of a character followed by the component, the component (including its prefix character) must be included even if the new value is the empty string.
The previous paragraph applies in particular to the
":
" before a <port> component, the "?
" before a <query> component, and the "#
" before a <fragment> component.
For the purposes of the above definitions, URLs must be parsed using the URL parsing rules defined in this specification.
Attribute | Component | Getter Condition | Prefix | Suffix | Setter Preprocessor | Setter Condition |
---|---|---|---|---|---|---|
protocol
| <scheme> | — | — | U+003A COLON (": ")
| Remove all trailing U+003A COLON (": ") characters
| The new value is not the empty string |
host
| <hostport> | input is hierarchical and uses a server-based naming authority | — | — | — | — |
hostname
| <host> | input is hierarchical and uses a server-based naming authority | — | — | Remove all leading U+002F SOLIDUS ("/ ") characters
| — |
port
| <port> | input is hierarchical, uses a server-based naming authority, and contained a <port> component (possibly an empty one) | — | — | Remove any characters in the new value that are not in the range U+0030 DIGIT ZERO .. U+0039 DIGIT NINE. If the resulting string is empty, set it to a single U+0030 DIGIT ZERO character ('0'). | — |
pathname
| <path> | input is hierarchical | — | — | If it has no leading U+002F SOLIDUS ("/ ") character, prepend a U+002F SOLIDUS ("/ ") character to the new value
| — |
search
| <query> | input is hierarchical, and contained a <query> component (possibly an empty one) | U+003F QUESTION MARK ("? ")
| — | Remove one leading U+003F QUESTION MARK ("? ") character, if any
| — |
hash
| <fragment> | input contained a <fragment> component (possibly an empty one) | U+0023 NUMBER SIGN ("# ")
| — | Remove one leading U+0023 NUMBER SIGN ("# ") character, if any
| — |
The table below demonstrates how the getter condition for search
results in different results
depending on the exact original syntax of the URL:
Input URL | search value
| Explanation |
---|---|---|
http://example.com/
| empty string | No <query> component in input URL. |
http://example.com/?
| ?
| There is a <query> component, but it is empty. The question mark in the resulting value is the prefix. |
http://example.com/?test
| ?test
| The <query> component has the value "test ".
|
http://example.com/?test#
| ?test
| The (empty) <fragment> component is not part of the <query> component. |
When a user agent is to fetch a resource, the following steps must be run:
If the resource is identified by the URL
about:blank
, then return the empty string
and abort these steps.
Perform the remaining steps asynchronously.
If the resource is identified by an absolute URL, and the resource is to be obtained using a idempotent action (such as an HTTP GET or equivalent), and it is already being downloaded for other reasons (e.g. another invocation of this algorithm), and the user agent is configured such that it is to reuse the data from the existing download instead of initiating a new one, then use the results of the existing download instead of starting a new one.
Otherwise, at a time convenient to the user and the user agent,
download (or otherwise obtain) the resource, applying the
semantics of the relevant specifications (e.g. performing an HTTP
GET or POST operation, or reading the file from disk, following
redirects, dereferencing javascript:
URLs, etc).
When the resource is available, queue a task that uses the resource as appropriate. If the resource can be processed incrementally, as, for instance, with a progressively interlaced JPEG or an HTML file, multiple tasks may be queued to process the data as it is downloaded. The task source for these tasks is the networking task source.
The offline application cache processing model introduces some changes to the networking model to handle the returning of cached resources.
The navigation processing model handles redirects itself, overriding the redirection handling that would be done by the fetching algorithm.
Whether the type sniffing rules apply to the fetched resource depends on the algorithm that invokes the rules — they are not always applicable.
User agents can implement a variety of transfer protocols, but this specification mostly defines behavior in terms of HTTP. [HTTP]
The HTTP GET method is equivalent to the default retrieval action of the protocol. For example, RETR in FTP. Such actions are idempotent and safe, in HTTP terms.
The HTTP response codes are equivalent to statuses in other protocols that have the same basic meanings. For example, a "file not found" error is equivalent to a 404 code, a server error is equivalent to a 5xx code, and so on.
The HTTP headers are equivalent to fields in other protocols that have the same basic meaning. For example, the the HTTP authentication headers are equivalent to the authentication aspects of the FTP protocol.
If there are any specific questions with what should be considered equivalent to what, let me know, and I'll make it more explicit for those cases.
Anything in this specification that refers to HTTP also applies
to HTTP-over-TLS, as represented by URLs
representing the https
scheme.
User agents should report certificate errors to the user and must either refuse to download resources sent with erroneous certificates or must act as if such resources were in fact served with no encryption.
Not doing so can result in users not noticing man-in-the-middle attacks.
If a user connects to a server with a self-signed certificate, the user agent could allow the connection but just act as if there had been no encryption. If the user agent instead allowed the user to override the problem and then displayed the page as if it was fully and safely encrypted, the user could be easily tricked into accepting man-in-the-middle connections.
If a user connects to a server with full encryption, but the page then refers to an external resource that has an expired certificate, then the user agent will act as if the resource was unavailable, possibly also reporting the problem to the user. If the user agent instead allowed the resource to be used, then an attacker could just look for "secure" sites that used resources from a different host and only apply man-in-the-middle attacks to that host, for example taking over scripts in the page.
It is imperative that the rules in this section be followed exactly. When a user agent uses different heuristics for content type detection than the server expects, security problems can occur. For example, if a server believes that the client will treat a contributed file as an image (and thus treat it as benign), but a Web browser believes the content to be HTML (and thus execute any scripts contained therein), the end user can be exposed to malicious content, making the user vulnerable to cookie theft attacks and other cross-site scripting attacks.
What explicit Content-Type metadata is associated with the resource (the resource's type information) depends on the protocol that was used to fetch the resource.
For HTTP resources, only the first Content-Type HTTP header, if any, contributes any type information; the explicit type of the resource is then the value of that header, interpreted as described by the HTTP specifications. If the Content-Type HTTP header is present but the value of the first such header cannot be interpreted as described by the HTTP specifications (e.g. because its value doesn't contain a U+002F SOLIDUS ('/') character), then the resource has no type information (even if there are multiple Content-Type HTTP headers and one of the other ones is syntactically correct). [HTTP]
For resources fetched from the file system, user agents should use platform-specific conventions, e.g. operating system extension/type mappings.
Extensions must not be used for determining resource types for resources fetched over HTTP.
For resources fetched over most other protocols, e.g. FTP, there is no type information.
The algorithm for extracting an encoding from a Content-Type, given a string s, is as follows. It either returns an encoding or nothing.
Find the first seven characters in s that are an ASCII case-insensitive match for the word "charset". If no such match is found, return nothing.
Skip any U+0009, U+000A, U+000C, U+000D, or U+0020 characters that immediately follow the word 'charset' (there might not be any).
If the next character is not a U+003D EQUALS SIGN ('='), return nothing.
Skip any U+0009, U+000A, U+000C, U+000D, or U+0020 characters that immediately follow the equals sign (there might not be any).
Process the next character as follows:
Return the string between this character and the next earliest occurrence of this character.
Return nothing.
Return the string from this character to the first U+0009, U+000A, U+000C, U+000D, U+0020, or U+003B character or the end of s, whichever comes first.
The above algorithm is a willful violation of the HTTP specification. [RFC2616]
The sniffed type of a resource must be found as follows:
If the user agent is configured to strictly obey Content-Type headers for this resource, then jump to the last step in this set of steps.
If the resource was fetched over an HTTP protocol and there is an HTTP Content-Type header and the value of the first such header has bytes that exactly match one of the following lines:
Bytes in Hexadecimal | Textual representation |
---|---|
74 65 78 74 2f 70 6c 61 69 6e | text/plain
|
74 65 78 74 2f 70 6c 61 69 6e 3b 20 63 68 61 72 73 65 74 3d 49 53 4f 2d 38 38 35 39 2d 31 | text/plain; charset=ISO-8859-1
|
74 65 78 74 2f 70 6c 61 69 6e 3b 20 63 68 61 72 73 65 74 3d 69 73 6f 2d 38 38 35 39 2d 31 | text/plain; charset=iso-8859-1
|
74 65 78 74 2f 70 6c 61 69 6e 3b 20 63 68 61 72 73 65 74 3d 55 54 46 2d 38 | text/plain; charset=UTF-8
|
...then jump to the text or binary section below.
Let official type be the type given by the Content-Type metadata for the resource, ignoring parameters. If there is no such type, jump to the unknown type step below. Comparisons with this type, as defined by MIME specifications, are done in an ASCII case-insensitive manner. [RFC2046]
If official type is "unknown/unknown" or "application/unknown", jump to the unknown type step below.
If official type ends in "+xml", or if it is either "text/xml" or "application/xml", then the sniffed type of the resource is official type; return that and abort these steps.
If official type is an image type supported by the user agent (e.g. "image/png", "image/gif", "image/jpeg", etc), then jump to the images section below, passing it the official type.
If official type is "text/html", then jump to the feed or HTML section below.
The sniffed type of the resource is official type.
The user agent may wait for 512 or more bytes of the resource to be available.
Let n be the smaller of either 512 or the number of bytes already available.
If n is 4 or more, and the first bytes of the resource match one of the following byte sets:
Bytes in Hexadecimal | Description |
---|---|
FE FF | UTF-16BE BOM |
FF FE | UTF-16LE BOM |
EF BB BF | UTF-8 BOM |
...then the sniffed type of the resource is "text/plain". Abort these steps.
If none of the first n bytes of the resource are binary data bytes then the sniffed type of the resource is "text/plain". Abort these steps.
If the first bytes of the resource match one of the byte sequences in the "pattern" column of the table in the unknown type section below, ignoring any rows whose cell in the "security" column says "scriptable" (or "n/a"), then the sniffed type of the resource is the type given in the corresponding cell in the "sniffed type" column on that row; abort these steps.
It is critical that this step not ever return a scriptable type (e.g. text/html), as otherwise that would allow a privilege escalation attack.
Otherwise, the sniffed type of the resource is "application/octet-stream".
Bytes covered by the following ranges are binary data bytes:
The user agent may wait for 512 or more bytes of the resource to be available.
Let stream length be the smaller of either 512 or the number of bytes already available.
For each row in the table below:
Let indexpattern be an index into the mask and pattern byte strings of the row.
Let indexstream be an index into the byte stream being examined.
Loop: If indexstream points beyond the end of the byte stream, then this row doesn't match, skip this row.
Examine the indexstreamth byte of the byte stream as follows:
If the "and" operator, applied to the indexstreamth byte of the stream and the indexpatternth byte of the mask, yield a value different that the indexpatternth byte of the pattern, then skip this row.
Otherwise, increment indexpattern to the next byte in the mask and pattern and indexstream to the next byte in the byte stream.
"WS" means "whitespace", and allows insignificant whitespace to be skipped when sniffing for a type signature.
If the indexstreamth byte of the stream is one of 0x09 (ASCII TAB), 0x0A (ASCII LF), 0x0C (ASCII FF), 0x0D (ASCII CR), or 0x20 (ASCII space), then increment only the indexstream to the next byte in the byte stream.
Otherwise, increment only the indexpattern to the next byte in the mask and pattern.
If indexpattern does not point beyond the end of the mask and pattern byte strings, then jump back to the loop step in this algorithm.
Otherwise, the sniffed type of the resource is the type given in the cell of the third column in that row; abort these steps.
If none of the first n bytes of the resource are binary data bytes then the sniffed type of the resource is "text/plain". Abort these steps.
Otherwise, the sniffed type of the resource is "application/octet-stream".
The table used by the above algorithm is:
Bytes in Hexadecimal | Sniffed type | Security | Comment | |
---|---|---|---|---|
Mask | Pattern | |||
FF FF DF DF DF DF DF DF DF FF DF DF DF DF | 3C 21 44 4F 43 54 59 50 45 20 48 54 4D 4C | text/html | Scriptable | The string "<!DOCTYPE HTML " in US-ASCII or compatible encodings, case-insensitively.
|
FF FF DF DF DF DF | WS 3C 48 54 4D 4C | text/html | Scriptable | The string "<HTML " in US-ASCII or compatible encodings, case-insensitively, possibly with leading spaces.
|
FF FF DF DF DF DF | WS 3C 48 45 41 44 | text/html | Scriptable | The string "<HEAD " in US-ASCII or compatible encodings, case-insensitively, possibly with leading spaces.
|
FF FF DF DF DF DF DF DF | WS 3C 53 43 52 49 50 54 | text/html | Scriptable | The string "<SCRIPT " in US-ASCII or compatible encodings, case-insensitively, possibly with leading spaces.
|
FF FF FF FF FF | 25 50 44 46 2D | application/pdf | Scriptable | The string "%PDF- ", the PDF signature.
|
FF FF FF FF FF FF FF FF FF FF FF | 25 21 50 53 2D 41 64 6F 62 65 2D | application/postscript | Safe | The string "%!PS-Adobe- ", the PostScript signature.
|
FF FF 00 00 | FE FF 00 00 | text/plain | n/a | UTF-16BE BOM |
FF FF 00 00 | FF FF 00 00 | text/plain | n/a | UTF-16LE BOM |
FF FF FF 00 | EF BB BF 00 | text/plain | n/a | UTF-8 BOM |
FF FF FF FF FF FF | 47 49 46 38 37 61 | image/gif | Safe | The string "GIF87a ", a GIF signature.
|
FF FF FF FF FF FF | 47 49 46 38 39 61 | image/gif | Safe | The string "GIF89a ", a GIF signature.
|
FF FF FF FF FF FF FF FF | 89 50 4E 47 0D 0A 1A 0A | image/png | Safe | The PNG signature. |
FF FF FF | FF D8 FF | image/jpeg | Safe | A JPEG SOI marker followed by the first byte of another marker. |
FF FF | 42 4D | image/bmp | Safe | The string "BM ", a BMP signature.
|
FF FF FF FF | 00 00 01 00 | image/vnd.microsoft.icon | Safe | A 0 word following by a 1 word, a Windows Icon file format signature. |
I'd like to add types like MPEG, AVI, Flash, Java, etc, to the above table.
User agents may support further types if desired, by implicitly adding to the above table. However, user agents should not use any other patterns for types already mentioned in the table above, as this could then be used for privilege escalation (where, e.g., a server uses the above table to determine that content is not HTML and thus safe from XSS attacks, but then a user agent detects it as HTML anyway and allows script to execute).
The column marked "security" is used by the algorithm in the
"text or binary" section, to avoid sniffing text/plain
content as a type that can be used for a
privilege escalation attack.
If the resource's official type is "image/svg+xml", then the sniffed type of the resource is its official type (an XML type).
Otherwise, if the first bytes of the resource match one of the byte sequences in the first column of the following table, then the sniffed type of the resource is the type given in the corresponding cell in the second column on the same row:
Bytes in Hexadecimal | Sniffed type | Comment |
---|---|---|
47 49 46 38 37 61 | image/gif | The string "GIF87a ", a GIF signature.
|
47 49 46 38 39 61 | image/gif | The string "GIF89a ", a GIF signature.
|
89 50 4E 47 0D 0A 1A 0A | image/png | The PNG signature. |
FF D8 FF | image/jpeg | A JPEG SOI marker followed by the first byte of another marker. |
42 4D | image/bmp | The string "BM ", a BMP signature.
|
00 00 01 00 | image/vnd.microsoft.icon | A 0 word following by a 1 word, a Windows Icon file format signature. |
Otherwise, the sniffed type of the resource is the same as its official type.
The user agent may wait for 512 or more bytes of the resource to be available.
Let s be the stream of bytes, and let s[i] represent the byte in s with position i, treating s as zero-indexed (so the first byte is at i=0).
If at any point this algorithm requires the user agent to determine the value of a byte in s which is not yet available, or which is past the first 512 bytes of the resource, or which is beyond the end of the resource, the user agent must stop this algorithm, and assume that the sniffed type of the resource is "text/html".
User agents are allowed, by the first step of this algorithm, to wait until the first 512 bytes of the resource are available.
Initialize pos to 0.
If s[0] is 0xEF, s[1] is 0xBB, and s[2] is 0xBF, then set pos to 3. (This skips over a leading UTF-8 BOM, if any.)
Loop start: Examine s[pos].
<
")If the bytes with positions pos to
pos+2 in s are
exactly equal to 0x21, 0x2D, 0x2D respectively (ASCII for "!--
"), then:
-->
"), then increase pos
by 3 and jump back to the previous step (the step labeled
loop start) in the overall algorithm in this section.If s[pos] is 0x21 (ASCII "!
"):
If s[pos] is 0x3F (ASCII "?
"):
Otherwise, if the bytes in s starting at pos match any of the sequences of bytes in the first column of the following table, then the user agent must follow the steps given in the corresponding cell in the second column of the same row.
Bytes in Hexadecimal | Requirement | Comment |
---|---|---|
72 73 73 | The sniffed type of the resource is "application/rss+xml"; abort these steps | The three ASCII characters "rss "
|
66 65 65 64 | The sniffed type of the resource is "application/atom+xml"; abort these steps | The four ASCII characters "feed "
|
72 64 66 3A 52 44 46 | Continue to the next step in this algorithm | The ASCII characters "rdf:RDF "
|
If none of the byte sequences above match the bytes in s starting at pos, then the sniffed type of the resource is "text/html". Abort these steps.
If, before the next ">", you find two xmlns* attributes with http://www.w3.org/1999/02/22-rdf-syntax-ns# and http://purl.org/rss/1.0/ as the namespaces, then the sniffed type of the resource is "application/rss+xml", abort these steps. (maybe we only need to check for http://purl.org/rss/1.0/ actually)
Otherwise, the sniffed type of the resource is "text/html".
For efficiency reasons, implementations may wish to implement this algorithm and the algorithm for detecting the character encoding of HTML documents in parallel.
Some DOM attributes are defined to reflect a particular content attribute. This means that on getting, the DOM attribute returns the current value of the content attribute, and on setting, the DOM attribute changes the value of the content attribute to the given value.
If a reflecting DOM attribute is a DOMString
attribute whose content attribute is defined to contain a
URL, then on getting, the DOM attribute must resolve the value of the content
attribute relative to the element and return the resulting
absolute URL if that was successful, or the empty
string otherwise; and on setting, must set the content attribute to
the specified literal value. If the content attribute is absent, the
DOM attribute must return the default value, if the content
attribute has one, or else the empty string.
If a reflecting DOM attribute is a DOMString
attribute whose content attribute is defined to contain one or more
URLs, then on getting, the DOM attribute
must split the content
attribute on spaces and return the concatenation of resolving each token URL to an
absolute URL relative to the element, with a single
U+0020 SPACE character between each URL, ignoring any tokens that
did not resolve successfully. If the content attribute is absent,
the DOM attribute must return the default value, if the content
attribute has one, or else the empty string. On setting, the DOM
attribute must set the content attribute to the specified literal
value.
If a reflecting DOM attribute is a DOMString
whose
content attribute is an enumerated attribute, and the
DOM attribute is limited to only known values, then, on
getting, the DOM attribute must return the conforming value
associated with the state the attribute is in (in its canonical
case), or the empty string if the attribute is in a state that has
no associated keyword value; and on setting, if the new value is an
ASCII case-insensitive match for one of the keywords
given for that attribute, then the content attribute must be set to
the conforming value associated with the state that the attribute
would be in if set to the given new value, otherwise, if the new
value is the empty string, then the content attribute must be
removed, otherwise, the setter must raise a SYNTAX_ERR
exception.
If a reflecting DOM attribute is a DOMString
but
doesn't fall into any of the above categories, then the getting and
setting must be done in a transparent, case-preserving manner.
If a reflecting DOM attribute is a boolean attribute, then on getting the DOM attribute must return true if the attribute is set, and false if it is absent. On setting, the content attribute must be removed if the DOM attribute is set to false, and must be set to have the same value as its name if the DOM attribute is set to true. (This corresponds to the rules for boolean content attributes.)
If a reflecting DOM attribute is a signed integer type
(long
) then, on getting, the content attribute must be
parsed according to the rules for parsing signed integers, and if that is
successful, and the value is in the range of the DOM attribute's
type, the resulting value must be returned. If, on the other hand,
it fails or returns an out of range value, or if the attribute is
absent, then the default value must be returned instead, or 0 if
there is no default value. On setting, the given value must be
converted to the shortest possible string representing the number as
a valid integer in base ten and then that string must
be used as the new content attribute value.
If a reflecting DOM attribute is an unsigned integer
type (unsigned long
) then, on getting, the content
attribute must be parsed according to the rules for parsing
non-negative integers, and if that is successful, and the
value is in the range of the DOM attribute's type, the resulting
value must be returned. If, on the other hand, it fails or returns
an out of range value, or if the attribute is absent, the default
value must be returned instead, or 0 if there is no default
value. On setting, the given value must be converted to the shortest
possible string representing the number as a valid
non-negative integer in base ten and then that string must be
used as the new content attribute value.
If a reflecting DOM attribute is an unsigned integer type
(unsigned long
) that is limited to only positive
non-zero numbers, then the behavior is similar to the previous
case, but zero is not allowed. On getting, the content attribute
must first be parsed according to the rules for parsing
non-negative integers, and if that is successful, and the
value is in the range of the DOM attribute's type, the resulting
value must be returned. If, on the other hand, it fails or returns
an out of range value, or if the attribute is absent, the default
value must be returned instead, or 1 if there is no default
value. On setting, if the value is zero, the user agent must fire an
INDEX_SIZE_ERR
exception. Otherwise, the given value
must be converted to the shortest possible string representing the
number as a valid non-negative integer in base ten and
then that string must be used as the new content attribute
value.
If a reflecting DOM attribute is a floating point number type
(float
) and it doesn't fall into one of the earlier
categories, then, on getting, the content attribute must be parsed
according to the rules for parsing floating point number
values, and if that is successful, and the value is in the
range of the DOM attribute's type, the resulting value must be
returned. If, on the other hand, it fails or returns an out of range
value, or if the attribute is absent, the default value must be
returned instead, or 0.0 if there is no default value. On setting,
the given value must be converted to the best representation
of the floating point number and then that string must be
used as the new content attribute value.
The values ±Infinity and NaN throw an exception on setting, as defined by WebIDL. [WEBIDL]
If a reflecting DOM attribute is of the type
DOMTokenList
, then on getting it must return a
DOMTokenList
object whose underlying string is the
element's corresponding content attribute. When the
DOMTokenList
object mutates its underlying string, the
content attribute must itself be immediately mutated. When the
attribute is absent, then the string represented by the
DOMTokenList
object is the empty string; when the
object mutates this empty string, the user agent must first add the
corresponding content attribute, and then mutate that attribute
instead. DOMTokenList
attributes are always
read-only. The same DOMTokenList
object must be
returned every time for each attribute.
If a reflecting DOM attribute has the type
HTMLElement
, or an interface that descends from
HTMLElement
, then, on getting, it must run the
following algorithm (stopping at the first point where a value is
returned):
document.getElementById()
method would find if it
was passed as its argument the current value of the corresponding
content attribute.On setting, if the given element has an id
attribute, then the content attribute must
be set to the value of that id
attribute. Otherwise, the DOM attribute must be set to the empty
string.
The HTMLCollection
,
HTMLFormControlsCollection
, and
HTMLOptionsCollection
interfaces represent various
lists of DOM nodes. Collectively, objects implementing these
interfaces are called collections.
When a collection is created, a filter and a root are associated with the collection.
For example, when the HTMLCollection
object for the document.images
attribute is
created, it is associated with a filter that selects only
img
elements, and rooted at the root of the
document.
The collection then represents a live view of the subtree rooted at the collection's root, containing only nodes that match the given filter. The view is linear. In the absence of specific requirements to the contrary, the nodes within the collection must be sorted in tree order.
The rows
list is
not in tree order.
An attribute that returns a collection must return the same object every time it is retrieved.
The HTMLCollection
interface represents a generic
collection of elements.
[Callable=namedItem] interface HTMLCollection { readonly attribute unsigned long length; [IndexGetter] Element item(in unsigned long index); [NameGetter] Element namedItem(in DOMString name); };
The object's indices of the supported indexed properties are the numbers in the range zero to one less than the number of nodes represented by the collection. If there are no such elements, then there are no supported indexed properties.
The length
attribute must return the number of nodes represented by the
collection.
The item(index)
method must return the indexth node in the collection. If there is no indexth node in the collection, then the method must
return null.
The names of the supported named properties consist
of the values of the name
attributes of each
a
, applet
, area
,
embed
, form
, frame
,
frameset
, iframe
, img
, and
object
element represented by the
collection with a name
attribute, plus
the list of IDs that the elements represented by the
collection have.
The namedItem(key)
method must return the first node
in the collection that matches the following requirements:
a
, applet
,
area
, embed
, form
,
frame
, frameset
, iframe
,
img
, or object
element with a name
attribute equal to key,
or,If no such elements are found, then the method must return null.
The HTMLFormControlsCollection
interface represents
a collection of listed elements in form
and fieldset
elements.
[Callable=namedItem] interface HTMLFormControlsCollection { readonly attribute unsigned long length; [IndexGetter] HTMLElement item(in unsigned long index); [NameGetter] Object namedItem(in DOMString name); };
The object's indices of the supported indexed properties are the numbers in the range zero to one less than the number of nodes represented by the collection. If there are no such elements, then there are no supported indexed properties.
The length
attribute must return the number of nodes represented by the
collection.
The item(index)
method must return the indexth node in the collection. If there is no indexth node in the collection, then the method must
return null.
The names of the supported named properties consist
of the values of all the id
and name
attributes of all the elements
represented by the collection.
The namedItem(name)
method must act according to the
following algorithm:
id
attribute or a name
attribute equal to name, then return that node and stop the
algorithm.id
attribute or a name
attribute equal to name, then return null and stop the algorithm.NodeList
object representing a
live view of the HTMLFormControlsCollection
object,
further filtered so that the only nodes in the
NodeList
object are those that have either an id
attribute or a name
attribute equal to name. The nodes in the NodeList
object
must be sorted in tree order.NodeList
object.The HTMLOptionsCollection
interface represents a
list of option
elements. It is always rooted on a
select
element and has attributes and methods that
manipulate that element's descendants.
[Callable=namedItem] interface HTMLOptionsCollection { attribute unsigned long length; [IndexGetter] HTMLOptionElement item(in unsigned long index); [NameGetter] Object namedItem(in DOMString name); void add(in HTMLElement element, in HTMLElement before); void add(in HTMLElement element, in long before); void remove(in long index); };
The object's indices of the supported indexed properties are the numbers in the range zero to one less than the number of nodes represented by the collection. If there are no such elements, then there are no supported indexed properties.
On getting, the length
attribute must return the number of nodes represented by the
collection.
On setting, the behavior depends on whether the new value is
equal to, greater than, or less than the number of nodes
represented by the collection at that time. If the
number is the same, then setting the attribute must do nothing. If
the new value is greater, then n new
option
elements with no attributes and no child nodes
must be appended to the select
element on which the
HTMLOptionsCollection
is rooted, where n is the difference between the two numbers (new
value minus old value). If the new value is lower, then the last
n nodes in the collection must be removed from
their parent nodes, where n is the difference
between the two numbers (old value minus new value).
Setting length
never removes
or adds any optgroup
elements, and never adds new
children to existing optgroup
elements (though it can
remove children from them).
The item(index)
method must return the indexth node in the collection. If there is no indexth node in the collection, then the method must
return null.
The names of the supported named properties consist
of the values of all the id
and name
attributes of all the elements
represented by the collection.
The namedItem(name)
method must act according to the
following algorithm:
id
attribute or a name
attribute equal to name, then return that node and stop the
algorithm.id
attribute or a name
attribute equal to name, then return null and stop the algorithm.NodeList
object representing a
live view of the HTMLOptionsCollection
object, further
filtered so that the only nodes in the NodeList
object
are those that have either an id
attribute or a name
attribute
equal to name. The nodes in the
NodeList
object must be sorted in tree
order.NodeList
object.The add(element, before)
method must act according to the following algorithm:
If element is not an option
or optgroup
element, then return and abort these
steps.
If element is an ancestor of the
select
element element on which the
HTMLOptionsCollection
is rooted, then throw a
HIERARCHY_REQUEST_ERR
exception.
If before is an element, but that
element isn't a descendant of the select
element
element on which the HTMLOptionsCollection
is rooted,
then throw a NOT_FOUND_ERR
exception.
If element and before are the same element, then return and abort these steps.
If before is a node, then let reference be that node. Otherwise, if before is an integer, and there is a beforeth node in the collection, let reference be that node. Otherwise, let reference be null.
If reference is not null, let parent be the parent node of reference. Otherwise, let parent
be the select
element element on which the
HTMLOptionsCollection
is rooted.
Act as if the DOM Core insertBefore()
method was invoked
on the parent node, with element as the first argument and reference as the second argument.
The remove(index)
method must act according to
the following algorithm:
If the number of nodes represented by the collection is zero, abort these steps.
If index is not a number greater than or equal to 0 and less than the number of nodes represented by the collection, let element be the first element in the collection. Otherwise, let element be the indexth element in the collection.
Remove element from its parent node.
The DOMTokenList
interface represents an interface
to an underlying string that consists of an unordered set of
unique space-separated tokens.
Which string underlies a particular DOMTokenList
object is defined when the object is created. It might be a content
attribute (e.g. the string that underlies the classList
object is the class
attribute), or it might be an
anonymous string (e.g. when a DOMTokenList
object is
passed to an author-implemented callback in the
datagrid
APIs).
[Stringifies] interface DOMTokenList { readonly attribute unsigned long length; [IndexGetter] DOMString item(in unsigned long index); boolean has(in DOMString token); void add(in DOMString token); void remove(in DOMString token); boolean toggle(in DOMString token); };
The length
attribute must return the number of unique tokens that
result from splitting the
underlying string on spaces. This is the length.
The object's indices of the supported indexed properties are the numbers in the range zero to length-1, unless the length is zero, in which case there are no supported indexed properties.
The item(index)
method must split the underlying string on spaces, sort
the resulting list of tokens by Unicode codepoint,
remove exact duplicates, and then return the indexth item in this list. If index is equal to or greater than the number of
tokens, then the method must return null.
The has(token)
method must run the following
algorithm:
INVALID_CHARACTER_ERR
exception and stop the
algorithm.The add(token)
method must run the following
algorithm:
INVALID_CHARACTER_ERR
exception and stop the
algorithm.DOMTokenList
object's underlying string
then stop the algorithm.DOMTokenList
object's underlying
string is not the empty string and the last character of that
string is not a space character, then append a U+0020
SPACE character to the end of that string.DOMTokenList
object's underlying string.The remove(token)
method must run the following
algorithm:
INVALID_CHARACTER_ERR
exception and stop the
algorithm.The toggle(token)
method must run the following
algorithm:
INVALID_CHARACTER_ERR
exception and stop the
algorithm.DOMTokenList
object's underlying string
then remove the given
token from the underlying string, and
stop the algorithm, returning false.DOMTokenList
object's underlying
string is not the empty string and the last character of that
string is not a space character, then append a U+0020
SPACE character to the end of that string.DOMTokenList
object's underlying string.Objects implementing the DOMTokenList
interface must
stringify to the object's
underlying string representation.
When a user agent is required to obtain a structured clone of an object, it must run the following algorithm, which either returns a separate object, or throws an exception.
Let input be the object being cloned.
Let memory be a list of objects, initially empty. (This is used to catch cycles.)
Let output be the object resulting from calling the internal structured cloning algorithm with input and memory.
Return output.
The internal structured cloning algorithm is always called with two arguments, input and memory, and its behavior depends on the type of input, as follows:
Return the undefined value.
Return the null value.
Return the false value.
Return the true value.
Return a newly constructed Number object with the same value as input.
Return a newly constructed String object with the same value as input.
Return a newly constructed Date object with the same value as input.
Return the null value.
If input is in memory, then throw a
NOT_SUPPORTED_ERR
exception and abort the overall
structured clone algorithm.
Otherwise, let new memory be a list consisting of the items in memory with the addition of input.
Create a new object, output, of the same type as input: either an Array or an Object.
For each property in input, add a corresponding property to output having the same name, and having a value created from invoking the internal structured cloning algorithm recursively with the value of the property as the "input" argument and new memory as the "memory" argument. The order of the properties in the input and output objects must be the same.
Return output.
The DOMStringMap
interface represents a set of
name-value pairs. When a DOMStringMap
object is
instantiated, it is associated with three algorithms, one for
getting getting the list of name-value pairs, one for setting names
to certain values, and one for deleting names.
[NameCreator, NameDeleter, NameGetter, NameSetter] interface DOMStringMap {};
The names of the supported named properties on a
DOMStringMap
object at any instant are the names of
each pair returned from the algorithm for getting the list of
name-value pairs at that instant.
When a DOMStringMap
object is indexed to retrieve a
named property name, the value returned must be
the value component of the name-value pair whose name component is
name in the list returned by the algorithm for
getting the list of name-value pairs.
When a DOMStringMap
object is indexed to create or
modify a named property name with value value, the algorithm for setting names to certain
values must be run, passing name as the name and
the result of converting value to a
DOMString
as the value.
When a DOMStringMap
object is indexed to delete a
named property named name, the algorithm for
deleting names must be run, passing name as the
name.
The DOMStringMap
interface definition
here is only intended for JavaScript environments. Other language
bindings will need to define how DOMStringMap
is to be
implemented for those languages.
DOM3 Core defines mechanisms for checking for interface support, and for obtaining implementations of interfaces, using feature strings. [DOM3CORE]
A DOM application can use the hasFeature(feature,
version)
method of the
DOMImplementation
interface with parameter values
"HTML
" and "5.0
" (respectively)
to determine whether or not this module is supported by the
implementation. In addition to the feature string "HTML
", the feature string "XHTML
" (with version string "5.0
") can
be used to check if the implementation supports XHTML. User agents
should respond with a true value when the hasFeature
method is queried with these values. Authors are cautioned, however,
that UAs returning true might not be perfectly compliant, and that
UAs returning false might well have support for features in this
specification; in general, therefore, use of this method is
discouraged.
The values "HTML
" and "XHTML
" (both with version "5.0
") should
also be supported in the context of the getFeature()
and isSupported()
methods, as defined by DOM3 Core.
The interfaces defined in this specification are not
always supersets of the interfaces defined in DOM2 HTML; some
features that were formerly deprecated, poorly supported, rarely
used or considered unnecessary have been removed. Therefore it is
not guaranteed that an implementation that supports "HTML
" "5.0
" also supports "HTML
" "2.0
".
The following DOMException
codes are defined in DOM
Core. [DOMCORE]
INDEX_SIZE_ERR
DOMSTRING_SIZE_ERR
HIERARCHY_REQUEST_ERR
WRONG_DOCUMENT_ERR
INVALID_CHARACTER_ERR
NO_DATA_ALLOWED_ERR
NO_MODIFICATION_ALLOWED_ERR
NOT_FOUND_ERR
NOT_SUPPORTED_ERR
INUSE_ATTRIBUTE_ERR
INVALID_STATE_ERR
SYNTAX_ERR
INVALID_MODIFICATION_ERR
NAMESPACE_ERR
INVALID_ACCESS_ERR
VALIDATION_ERR
TYPE_MISMATCH_ERR
SECURITY_ERR
NETWORK_ERR
ABORT_ERR
URL_MISMATCH_ERR
QUOTA_EXCEEDED_ERR
UNAVAILABLE_SCRIPT_ERR
PARSE_ERR
SERIALISE_ERR
There is an implied strong reference from any DOM attribute that returns a pre-existing object to that object.
For example, the document.location
attribute means
that there is a strong reference from a Document
object to its Location
object. Similarly, there is
always a strong reference from a Document
to any
descendant nodes, and from any node to its owner
Document
.