Various mechanisms can cause author-provided executable code to run in the context of a document. These mechanisms include, but are probably not limited to:
script
elements.javascript:
URLs (e.g. the src
attribute of img
elements, or an @import
rule in a CSS
style
element block).addEventListener()
, by explicit event handler
content attributes, by event handler IDL
attributes, or otherwise.Scripting is enabled in a browsing context when all of the following conditions are true:
Scripting is disabled in a browsing context when any of the above conditions are false (i.e. when scripting is not enabled).
Scripting is enabled for a
node if the Document
object of the node (the
node itself, if it is itself a Document
object) has an
associated browsing context, and scripting is enabled in that
browsing context.
Scripting is disabled for a node if there is no such browsing context, or if scripting is disabled in that browsing context.
A script has:
The characteristics of the script execution environment depend on the language, and are not defined by this specification.
In JavaScript, the script execution environment consists of the interpreter, the stack of execution contexts, the global code and function code and the Function objects resulting, and so forth.
Each code entry-point represents a block of executable code that the script exposes to other scripts and to the user agent.
Each Function object in a JavaScript script execution environment has a corresponding code entry-point, for instance.
The main program code of the script, if any, is the initial code entry-point. Typically, the code corresponding to this entry-point is executed immediately after the script is parsed.
In JavaScript, this corresponds to the execution context of the global code.
An object that provides the APIs that the code can use.
This is typically a Window
object. In JavaScript, this corresponds to the global
object.
When a script's global object is an empty object, it can't do anything that interacts with the environment.
If the script's global object is a
Window
object, then in JavaScript, the ThisBinding of
the global execution context for this script must be the
Window
object's WindowProxy
object,
rather than the global object. [ECMA262]
This is a willful violation of the
JavaScript specification current at the time of writing
(ECMAScript edition 5, as defined in section 10.4.1.1 Initial
Global Execution Context, step 3). The JavaScript specification
requires that the this
keyword in the global
scope return the global object, but this is not compatible with
the security design prevalent in implementations as specified
herein. [ECMA262]
A browsing context that is assigned responsibility for actions taken by the script.
When a script creates and navigates a new top-level browsing
context, the opener
attribute of the new browsing context's
Window
object will be set to the script's
browsing context's WindowProxy
object.
A Document
that is assigned responsibility for
actions taken by the script.
When a script fetches a resource, the current address of the
script's document will be used to set the Referer
(sic) header.
A character encoding, set when the script is created, used to encode URLs. If the character encoding is set from another source, e.g. a document's character encoding, then the script's URL character encoding must follow the source, so that if the source's changes, so does the script's.
A URL, set when the script is created, used to resolve relative URLs. If the base URL is set from another source, e.g. a document base URL, then the script's base URL must follow the source, so that if the source's changes, so does the script's.
When a user agent is to jump to a code entry-point for a script, for example to invoke an event listener defined in that script, the user agent must run the following steps:
If the script's global object is a
Window
object whose Document
object is
not fully active, then abort these steps without doing
anything. The callback is not fired.
Set the entry script to be the script being invoked.
Make the script execution environment for the script execute the code for the given code entry-point.
Set the entry script back to whatever it was when this algorithm started.
This algorithm is not invoked by one script calling another.
When the specification says that a script is to be created, given some script source, its scripting language, a global object, a browsing context, a URL character encoding, and a base URL, the user agent must run the following steps:
If scripting is disabled for browsing context passed to this algorithm, then abort these steps, as if the script did nothing but return void.
Set up a script execution environment as appropriate for the scripting language.
Parse/compile/initialize the source of the script using the script execution environment, as appropriate for the scripting language, and thus obtain the list of code entry-points for the script. If the semantics of the scripting language and the given source code are such that there is executable code to be immediately run, then the initial code entry-point is the entry-point for that code.
Set up the script's global object, the script's browsing context, the script's document, the script's URL character encoding, and the script's base URL from the settings passed to this algorithm.
If all the steps above succeeded (in particular, if the script was compiled successfully), Jump to the script's initial code entry-point.
Otherwise, report the error using the onerror
event handler of the script's global
object. If the error is still not handled after this, then
the error may be reported to the user.
When the user agent is to create an impotent script, given some script source, its scripting language, and a browsing context, the user agent must create a script, using the given script source and scripting language, using a new empty object as the global object, and using the given browsing context as the browsing context. The URL character encoding and base URL for the resulting script are not important as no APIs are exposed to the script.
When the specification says that a script is to be created from a node node, given some script source and its scripting language, the user agent must create a script, using the given script source and scripting language, and using the script settings determined from the node node.
The script settings determined from the node node are computed as follows:
Let document be the
Document
of node (or node itself if it is a
Document
).
The browsing context is the browsing context of document.
The global object is the Window
object of
document.
The URL character encoding is the character encoding of document. (This is a reference, not a copy.)
The base URL is the base URL of document. (This is a reference, not a copy.)
User agents may impose resource limitations on scripts, for
example CPU quotas, memory limits, total execution time limits, or
bandwidth limitations. When a script exceeds a limit, the user agent
may either throw a QUOTA_EXCEEDED_ERR
exception, abort
the script without an exception, prompt the user, or throttle script
execution.
For example, the following script never terminates. A user agent could, after waiting for a few seconds, prompt the user to either terminate the script or let it continue.
<script> while (true) { /* loop */ } </script>
User agents are encouraged to allow users to disable scripting
whenever the user is prompted either by a script (e.g. using the
window.alert()
API) or because of a
script's actions (e.g. because it has exceeded a time limit).
If scripting is disabled while a script is executing, the script should be terminated immediately.
Whenever an uncaught runtime script error occurs in one of the
scripts associated with a Document
, the user agent must
report the error using the onerror
event handler of the script's global
object. If the error is still not handled after this, then
the error may be reported to the user.
When the user agent is required to report an error error using the event handler onerror, it must run these steps, after which the error is either handled or not handled:
Function
The function must be invoked with three arguments. The three
arguments passed to the function are all DOMString
s;
the first must give the message that the UA is considering
reporting, the second must give the absolute URL of
the resource in which the error occurred, and the third must give
the line number in that resource on which the error occurred.
If the function returns false, then the error is handled. Otherwise, the error is not handled.
Any uncaught exceptions thrown or errors caused by this function may be reported to the user immediately after the error that the function was called for; the report an error algorithm must not be used to handle exceptions thrown or errors caused by this function.
The error is not handled.
To coordinate events, user interaction, scripts, rendering, networking, and so forth, user agents must use event loops as described in this section.
There must be at least one event loop per user agent, and at most one event loop per unit of related similar-origin browsing contexts.
When there is more than one event loop for a unit of related browsing contexts, complications arise when a browsing context in that group is navigated such that it switches from one unit of related similar-origin browsing contexts to another. This specification does not currently describe how to handle these complications.
An event loop always has at least one browsing context. If an event loop's browsing contexts all go away, then the event loop goes away as well. A browsing context always has an event loop coordinating its activities.
Other specifications can define new kinds of event loops that aren't associated with browsing contexts; in particular, the Web Workers specification does so.
An event loop has one or more task queues. A task queue is an ordered list of tasks, which can be:
Asynchronously dispatching an Event
object at a
particular EventTarget
object is a task.
Not all events are dispatched using the task queue, many are dispatched synchronously during other tasks.
The HTML parser tokenizing one or more bytes, and then processing any resulting tokens, is typically a task.
Calling a callback asynchronously is a task.
When an algorithm fetches a resource, if the fetching occurs asynchronously then the processing of the resource once some or all of the resource is available is a task.
Some elements have tasks that trigger in response to DOM manipulation, e.g. when that element is inserted into the document.
When a user agent is to queue a task, it must add the given task to one of the task queues of the relevant event loop. All the tasks from one particular task source (e.g. the callbacks generated by timers, the events dispatched for mouse movements, the tasks queued for the parser) must always be added to the same task queue, but tasks from different task sources may be placed in different task queues.
For example, a user agent could have one task queue for mouse and key events (the user interaction task source), and another for everything else. The user agent could then give keyboard and mouse events preference over other tasks three quarters of the time, keeping the interface responsive but not starving other task queues, and never processing events from any one task source out of order.
Each task that is queued onto a task queue of
an event loop defined by this specification is
associated with a Document
; if the task was queued in
the context of an element, then it is the element's
Document
; if the task was queued in the context of a
browsing context, then it is the browsing
context's active document at the time the task
was queued; if the task was queued by or for a script then the document is the
script's document.
A user agent is required to have one storage mutex. This mutex is used to control access to shared state like cookies. At any one point, the storage mutex is either free, or owned by a particular event loop or instance of the fetching algorithm.
Whenever a script calls into a plugin, and whenever a plugin calls into a script, the user agent must release the storage mutex.
An event loop must continually run through the following steps for as long as it exists:
Run the oldest task on one
of the event loop's task
queues, ignoring tasks whose associated
Document
s are not fully active. The user
agent may pick any task queue.
If the storage mutex is now owned by the event loop, release it so that it is once again free.
Remove that task from its task queue.
If necessary, update the rendering or user interface of any
Document
or browsing context to reflect
the current state.
Return to the first step of the event loop.
When the user agent is to provide a stable state, if any asynchronously-running algorithms are awaiting a stable state, then the user agent must run their synchronous section and then resume running their asynchronous algorithm (if appropriate).
A synchronous section never mutates the DOM, runs any script, or has any other side-effects.
Steps in synchronous sections are marked with ⌛.
When an algorithm says to spin the event loop until a condition goal is met, the user agent must run the following steps:
Let task source be the task source of the currently running task.
Stop the currently running task, allowing the event loop to resume, but continue these steps asynchronously.
This causes the event loop to move on to the second step of its processing model (defined above).
Wait until the condition goal is met.
Queue a task to continue running these steps, using the task source task source. Wait until this task runs before continuing these steps.
Return to the caller.
Some of the algorithms in this specification, for historical reasons, require the user agent to pause while running a task until a condition goal is met. This means running the following steps:
If any asynchronously-running algorithms are awaiting a stable state, then run their synchronous section and then resume running their asynchronous algorithm. (See the event loop processing model definition above for details.)
If necessary, update the rendering or user interface of any
Document
or browsing context to reflect
the current state.
Wait until the condition goal is met. While a user agent has a paused task, the corresponding event loop must not run further tasks, and any script in the currently running task must block. User agents should remain responsive to user input while paused, however, albeit in a reduced capacity since the event loop will not be doing anything.
When a user agent is to obtain the storage mutex as part of running a task, it must run through the following steps:
If the storage mutex is already owned by this task's event loop, then abort these steps.
Otherwise, pause until the storage mutex can be taken by the event loop.
Take ownership of the storage mutex.
The following task sources are used by a number of mostly unrelated features in this and other specifications.
This task source is used for features that react to DOM manipulations, such as things that happen asynchronously when an element is inserted into the document.
This task source is used for features that react to user interaction, for example keyboard or mouse input.
Asynchronous events sent in response to user input (e.g. click
events) must be dispatched using
tasks queued with the user interaction task
source. [DOMEVENTS]
This task source is used for features that trigger in response to network activity.
This task source is used to queue calls to history.back()
and similar
APIs.
javascript:
URL schemeWhen a URL using the javascript:
scheme is dereferenced, the user agent must run
the following steps:
Let the script source be the string obtained using the
content retrieval operation defined for javascript:
URLs. [JSURL]
Use the appropriate step from the following list:
javascript:
URL, and the source browsing context for that
navigation, if any, has scripting disabledLet result be void.
javascript:
URL, and the active document of that browsing
context has the same origin as the script given by
that URLLet address be the address of the active document of the browsing context being navigated.
If address is about:blank
,
and the browsing context being navigated has a
creator browsing context, then let address be the address of the creator
Document
instead.
Create a
script from the Document
node of the
active document, using the aforementioned script
source, and assuming the scripting language is JavaScript.
Let result be the return value of the initial code entry-point of this script. If an exception was raised, let result be void instead. (The result will be void also if scripting is disabled.)
When it comes time to set the document's address in the navigation algorithm, use address as the override URL.
Let result be void.
If the result of executing the script is void (there is no return value), then the URL must be treated in a manner equivalent to an HTTP resource with an HTTP 204 No Content response.
Otherwise, the URL must be treated in a manner equivalent to an
HTTP resource with a 200 OK response whose Content-Type metadata is
text/html
and whose response body is the return value
converted to a string value.
Certain contexts, in particular img
elements, ignore the Content-Type
metadata.
So for example a javascript:
URL for a
src
attribute of an
img
element would be evaluated in the context of an
empty object as soon as the attribute is set; it would then be
sniffed to determine the image type and decoded as an image.
A javascript:
URL in an href
attribute of an a
element would only be evaluated when the link was followed.
The src
attribute of an
iframe
element would be evaluated in the context of
the iframe
's own browsing context; once
evaluated, its return value (if it was not void) would replace that
browsing context's document, thus changing the
variables visible in that browsing context.
Many objects can have event handlers specified. These act as bubbling event listeners for the object on which they are specified.
An event handler can either
have the value null or be set to a Function
object. Initially, event handlers must be set to
null.
Event handlers are exposed in one or two ways.
The first way, common to all event handlers, is as an event handler IDL attribute.
The second way is as an event handler content attribute. Event handlers
on HTML elements and some of the event handlers on
Window
objects are exposed in this way.
Event handler IDL attributes, on setting, must set the corresponding event handler to their new value, and on getting, must return whatever the current value of the corresponding event handler is (possibly null).
If an event handler IDL attribute exposes an event handler of an object that doesn't exist, it must always return null on getting and must do nothing on setting.
This can happen in particular for event handler IDL attribute on
body
elements that do not have corresponding
Window
objects.
Certain event handler IDL attributes have additional
requirements, in particular the onmessage
attribute of
MessagePort
objects.
Event handler content attributes, when specified, must
contain valid JavaScript code which, when parsed, would match the
FunctionBody
production after automatic
semicolon insertion. [ECMA262]
When an event
handler content attribute is set, if the element is owned by
a Document
that is in a browsing context,
and scripting is enabled for
that browsing context, the user agent must run the
following steps to create a script after setting the content
attribute to its new value:
Set the corresponding event handler to null.
Set up a script execution environment for JavaScript.
Let body be the event handler content attribute's new value.
If body is not parsable as FunctionBody or if parsing detects an early error then abort these steps.
FunctionBody is defined in ECMAScript edition 5 section 13 Function Definition. Early error is defined in ECMAScript edition 5 section 16 Errors. [ECMA262]
If body begins with a Directive Prologue that contains a Use Strict Directive then let strict be true, otherwise let strict be false.
The terms "Directive Prologue" and "Use Strict Directive" are defined in ECMAScript edition 5 section 14.1 Directive Prologues and the Use Strict Directive. [ECMA262]
Using the script execution environment created above, create a function object (as defined in ECMAScript edition 5 section 13.2 Creating Function Objects), with:
Document
, the
global environment).NewObjectEnvironment() is defined in ECMAScript edition 5 section 10.2.2.3 NewObjectEnvironment (O, E). [ECMA262]
Let this new function be the only entry in the script's list of code entry-points.
Set up the script's global object, the script's browsing context, the script's document, the script's URL character encoding, and the script's base URL from the script settings determined from the node on which the attribute is being set.
Set the corresponding event handler to the aforementioned function.
When an event handler content attribute is removed, the user agent must set the corresponding event handler to null.
When an event handler content attribute is set on an
element owned by a Document
that is not in a
browsing context, the corresponding event handler is
not changed.
All event handlers on an object, whether an element
or some other object, and whether set to null or to a
Function
object, must be registered as event listeners
on the object when it is created, as if the addEventListener()
method on the object's EventTarget
interface had been
invoked, with the event type (type
argument) equal to the type corresponding to the event handler (the
event handler event type), the listener set to be a
target and bubbling phase listener (useCapture argument set to
false), and the event listener itself (listener argument) set to do
nothing while the event handler's value is not a
Function
object, and set to invoke the call()
callback of the
Function
object associated with the event handler
otherwise.
Event handlers therefore always fire before event listeners
attached using addEventListener()
.
The listener argument is emphatically not the event handler itself.
The interfaces implemented by the event object do not influence whether an event handler is triggered or not.
When an event handler's
Function
object is invoked, its call()
callback must be invoked
with one argument, set to the Event
object of the event
in question.
The handler's return value must then be processed as follows:
mouseover
If the return value is a boolean with the value true, then the event must be canceled.
BeforeUnloadEvent
objectIf the return value is a string, and the event object's
returnValue
attribute's value is the empty string, then set the returnValue
attribute's value to the return value.
If the return value is a boolean with the value false, then the event must be canceled.
The Function
interface represents a function in the
scripting language being used. It is represented in IDL as
follows:
[Callback=FunctionOnly, NoInterfaceObject] interface Function { any call(in any... arguments); };
The call(...)
method is the object's callback.
In JavaScript, any Function
object implements this interface.
If the Function
object is a JavaScript Function
, then when it is invoked by the user agent,
the user agent must set the thisArg (as defined
by ECMAScript edition 5 section 10.4.3 Entering Function Code) to
the event handler's object. [ECMA262]
For example, the following document fragment:
<body onload="alert(this)" onclick="alert(this)">
...leads to an alert saying "[object Window]
" when the document is loaded,
and an alert saying "[object HTMLBodyElement]
" whenever the user
clicks something in the page.
The return value of the function affects whether the event is
canceled or not: as described above, if
the return value is false, the event is canceled (except for mouseover
events, where the return
value has to be true to cancel the event). With beforeunload
events, the value is
instead used to determine the message to show the user.
Document
objects, and Window
objectsThe following are the event handlers (and their
corresponding event handler
event types) that must be supported by all HTML
elements, as both content attributes and IDL attributes, and
on Document
and Window
objects, as IDL
attributes.
Event handler | Event handler event type |
---|---|
onabort | abort
|
oncanplay | canplay
|
oncanplaythrough | canplaythrough
|
onchange | change
|
onclick | click
|
oncontextmenu | contextmenu
|
oncuechange | cuechange
|
ondblclick | dblclick
|
ondrag | drag
|
ondragend | dragend
|
ondragenter | dragenter
|
ondragleave | dragleave
|
ondragover | dragover
|
ondragstart | dragstart
|
ondrop | drop
|
ondurationchange | durationchange
|
onemptied | emptied
|
onended | ended
|
oninput | input
|
oninvalid | invalid
|
onkeydown | keydown
|
onkeypress | keypress
|
onkeyup | keyup
|
onloadeddata | loadeddata
|
onloadedmetadata | loadedmetadata
|
onloadstart | loadstart
|
onmousedown | mousedown
|
onmousemove | mousemove
|
onmouseout | mouseout
|
onmouseover | mouseover
|
onmouseup | mouseup
|
onmousewheel | mousewheel
|
onpause | pause
|
onplay | play
|
onplaying | playing
|
onprogress | progress
|
onratechange | ratechange
|
onreadystatechange | readystatechange
|
onreset | reset
|
onseeked | seeked
|
onseeking | seeking
|
onselect | select
|
onshow | show
|
onstalled | stalled
|
onsubmit | submit
|
onsuspend | suspend
|
ontimeupdate | timeupdate
|
onvolumechange | volumechange
|
onwaiting | waiting
|
The following are the event handlers (and their
corresponding event handler
event types) that must be supported by all HTML
elements other than body
, as both content
attributes and IDL attributes, and on Document
objects,
as IDL attributes:
Event handler | Event handler event type |
---|---|
onblur | blur
|
onerror | error
|
onfocus | focus
|
onload | load
|
onscroll | scroll
|
The following are the event handlers (and their
corresponding event handler
event types) that must be supported by Window
objects, as IDL attributes on the Window
object, and
with corresponding content attributes and IDL attributes exposed on
the body
and frameset
elements:
Event handler | Event handler event type |
---|---|
onafterprint | afterprint
|
onbeforeprint | beforeprint
|
onbeforeunload | beforeunload
|
onblur | blur
|
onerror | error
|
onfocus | focus
|
onhashchange | hashchange
|
onload | load
|
onmessage | message
|
onoffline | offline
|
ononline | online
|
onpagehide | pagehide
|
onpageshow | pageshow
|
onpopstate | popstate
|
onredo | redo
|
onresize | resize
|
onscroll | scroll
|
onstorage | storage
|
onundo | undo
|
onunload | unload
|
The onerror
handler is also used for reporting script errors.
Certain operations and methods are defined as firing events on
elements. For example, the click()
method on the HTMLElement
interface is defined as
firing a click
event on the
element. [DOMEVENTS]
Firing a simple event named e means that an event with the name e, which does not bubble (except where otherwise
stated) and is not cancelable (except where otherwise stated), and
which uses the Event
interface, must be dispatched at
the given target.
Firing a synthetic
mouse event named e means that an event
with the name e, which does not bubble (except
where otherwise stated) and is not cancelable (except where
otherwise stated), and which uses the MouseEvent
interface, must be dispatched at the given target. The event object
must have its screenX
, screenY
, clientX
, clientY
, and button
attributes
set to 0, its ctrlKey
, shiftKey
, altKey
, and metaKey
attributes set according to the current
state of the key input device, if any (false for any keys that are
not available), its detail
attribute set to 1,
and its relatedTarget
attribute set to null.
The getModifierState()
method on the object
must return values appropriately describing the state of the key
input device at the time the event is created.
Firing a click
event means firing a synthetic mouse event named click
, which bubbles and is
cancelable.
The default action of these events is to do nothing except where otherwise stated.
Window
objectWhen an event is dispatched at a DOM node in a
Document
in a browsing context, if the
event is not a load
event, the user
agent must also dispatch the event to the Window
, as
follows:
Window
object before propagating to any of the nodes,
as if the Window
object was the parent of the
Document
in the dispatch chain.Window
object at the end of the phase, unless bubbling
has been prevented, again as if the Window
object was
the parent of the Document
in the dispatch chain.The atob()
and btoa()
methods allow authors to
transform content to and from the base64 encoding.
[Supplemental, NoInterfaceObject] interface WindowBase64 { DOMString btoa(in DOMString btoa); DOMString atob(in DOMString atob); }; Window implements WindowBase64;
In these APIs, for mnemonic purposes, the "b" can be considered to stand for "binary", and the "a" for "ASCII". In practice, though, for primarily historical reasons, both the input and output of these functions are Unicode strings.
btoa
( data )Takes the input data, in the form of a Unicode string containing only characters in the range U+0000 to U+00FF, each representing a binary byte with values 0x00 to 0xFF respectively, and converts it to its base64 representation, which it returns.
Throws an INVALID_CHARACTER_ERR
exception if the
input string contains any out-of-range characters.
atob
( data )Takes the input data, in the form of a Unicode string containing base64-encoded binary data, decodes it, and returns a string consisting of characters in the range U+0000 to U+00FF, each representing a binary byte with values 0x00 to 0xFF respectively, corresponding to that binary data.
Throws an INVALID_CHARACTER_ERR
exception if the
input string is not valid base64 data.
The WindowBase64
interface adds to the
Window
interface and the WorkerUtils
interface (part of Web Workers).
The btoa()
method must throw an INVALID_CHARACTER_ERR
exception if
the method's first argument contains any character whose code point
is greater than U+00FF. Otherwise, the user agent must convert that
argument to a sequence of octets whose nth octet
is the eight-bit representation of the code point of the nth character of the argument, and then must apply
the base64 algorithm to that sequence of octets, and return the
result. [RFC4648]
The atob()
method must run the following steps to parse the string passed in
the method's first argument:
Let input be the string being parsed.
Let position be a pointer into input, initially pointing at the start of the string.
If the length of input divides by 4 leaving no remainder, then: if input ends with one or two U+003D EQUALS SIGN (=) characters, remove them from input.
If the length of input divides by 4
leaving a remainder of 1, throw an
INVALID_CHARACTER_ERR
exception and abort these
steps.
If input contains a character that is not
in the following list of characters and character ranges, throw an
INVALID_CHARACTER_ERR
exception and abort these
steps:
Let output be a string, initially empty.
Let buffer be a buffer that can have bits appended to it, initially empty.
While position does not point past the end of input, run these substeps:
Find the character pointed to by position in the first column of the following table. Let n be the number given in the second cell of the same row.
Character | Number |
---|---|
A | 0 |
B | 1 |
C | 2 |
D | 3 |
E | 4 |
F | 5 |
G | 6 |
H | 7 |
I | 8 |
J | 9 |
K | 10 |
L | 11 |
M | 12 |
N | 13 |
O | 14 |
P | 15 |
Q | 16 |
R | 17 |
S | 18 |
T | 19 |
U | 20 |
V | 21 |
W | 22 |
X | 23 |
Y | 24 |
Z | 25 |
a | 26 |
b | 27 |
c | 28 |
d | 29 |
e | 30 |
f | 31 |
g | 32 |
h | 33 |
i | 34 |
j | 35 |
k | 36 |
l | 37 |
m | 38 |
n | 39 |
o | 40 |
p | 41 |
q | 42 |
r | 43 |
s | 44 |
t | 45 |
u | 46 |
v | 47 |
w | 48 |
x | 49 |
y | 50 |
z | 51 |
0 | 52 |
1 | 53 |
2 | 54 |
3 | 55 |
4 | 56 |
5 | 57 |
6 | 58 |
7 | 59 |
8 | 60 |
9 | 61 |
+ | 62 |
/ | 63 |
Append to buffer the six bits corresponding to number, most significant bit first.
If buffer has accumulated 24 bits, interpret them as three 8-bit big-endian numbers. Append the three characters with code points equal to those numbers to output, in the same order, and then empty buffer.
Advance position by one character.
If buffer is not empty, it contains either 12 or 18 bits. If it contains 12 bits, discard the last four and interpret the remaining eight as an 8-bit big-endian number. If it contains 18 bits, discard the last two and interpret the remaining 16 as two 8-bit big-endian numbers. Append the one or two characters with code points equal to those one or two numbers to output, in the same order.
The discarded bits mean that, for instance, atob("YQ")
and atob("YR")
both return "a
".
Return output.
Some base64 encoders add newlines or other
whitespace to their output. The atob()
method throws an
exception if its input contains characters other than those
described by the regular expression bracket expression [+/=0-9A-Za-z]
, so other characters need to be
removed before atob()
is
used for decoding.