This section defines an event-based drag-and-drop mechanism.
This specification does not define exactly what a drag-and-drop operation actually is.
On a visual medium with a pointing device, a drag operation could
be the default action of a mousedown
event that is followed by a
series of mousemove
events, and
the drop could be triggered by the mouse being released.
When using an input modality other than a pointing device, users would probably have to explicitly indicate their intention to perform a drag-and-drop operation, stating what they wish to drag and where they wish to drop it, respectively.
However it is implemented, drag-and-drop operations must have a starting point (e.g. where the mouse was clicked, or the start of the selection or element that was selected for the drag), may have any number of intermediate steps (elements that the mouse moves over during a drag, or elements that the user picks as possible drop points as he cycles through possibilities), and must either have an end point (the element above which the mouse button was released, or the element that was finally selected), or be canceled. The end point must be the last element selected as a possible drop point before the drop occurs (so if the operation is not canceled, there must be at least one element in the middle step).
This section is non-normative.
To make an element draggable is simple: give the element a draggable
attribute, and set an event
listener for dragstart
that
stores the data being dragged.
The event handler typically needs to check that it's not a text
selection that is being dragged, and then needs to store data into
the DataTransfer
object and set the allowed effects
(copy, move, link, or some combination).
For example:
<p>What fruits do you like?</p> <ol ondragstart="dragStartHandler(event)"> <li draggable="true" data-value="fruit-apple">Apples</li> <li draggable="true" data-value="fruit-orange">Oranges</li> <li draggable="true" data-value="fruit-pear">Pears</li> </ol> <script> var internalDNDType = 'text/x-example'; // set this to something specific to your site function dragStartHandler(event) { if (event.target instanceof HTMLLIElement) { // use the element's data-value="" attribute as the value to be moving: event.dataTransfer.setData(internalDNDType, event.target.dataset.value); event.dataTransfer.effectAllowed = 'move'; // only allow moves } else { event.preventDefault(); // don't allow selection to be dragged } } </script>
To accept a drop, the drop target has to have a dropzone
attribute and listen to the
drop
event.
The value of the dropzone
attribute specifies what kind of data to accept (e.g. "string:text/plain
" to accept any text strings, or
"file:image/png
" to accept a PNG image file) and what
kind of feedback to give (e.g. "move
" to indicate that
the data will be moved).
Instead of using the dropzone
attribute, a drop target can
handle the dragenter
event (to
report whether or not the drop target is to accept the drop) and the
dragover
event (to specify what
feedback is to be shown to the user).
The drop
event allows the actual
drop to be performed. This event needs to be canceled, so that the
dropEffect
attribute's value can be used by the source (otherwise it's
reset).
For example:
<p>Drop your favorite fruits below:</p> <ol dropzone="move string:text/x-example" ondrop="dropHandler(event)"> <!-- don't forget to change the "text/x-example" type to something specific to your site --> </ol> <script> var internalDNDType = 'text/x-example'; // set this to something specific to your site function dropHandler(event) { var li = document.createElement('li'); var data = event.dataTransfer.getData(internalDNDType); if (data == 'fruit-apple') { li.textContent = 'Apples'; } else if (data == 'fruit-orange') { li.textContent = 'Oranges'; } else if (data == 'fruit-pear') { li.textContent = 'Pears'; } else { li.textContent = 'Unknown Fruit'; } event.target.appendChild(li); } </script>
To remove the original element (the one that was dragged) from
the display, the dragend
event
can be used.
For our example here, that means updating the original markup to handle that event:
<p>What fruits do you like?</p> <ol ondragstart="dragStartHandler(event)" ondragend="dragEndHandler(event)"> ...as before... </ol> <script> function dragStartHandler(event) { // ...as before... } function dragEndHandler(event) { // remove the dragged element event.target.parentNode.removeChild(event.target); } </script>
The data that underlies a drag-and-drop operation, known as the drag data store, consists of the following information:
A drag data store item list, which is a list of items representing the dragged data, each consisting of the following information:
The kind of data:
Text.
Binary data with a file name.
A Unicode string giving the type or format of the data, generally given by a MIME type. Some values that are not MIME types are special-cased for legacy reasons. The API does not enforce the use of MIME types; other values can be used as well. In all cases, however, the values are all converted to ASCII lowercase by the API.
Strings that contain space characters cannot be used with the dropzone
attribute, so authors are
encouraged to use only MIME types
or custom strings (without spaces).
There is a limit of one Plain Unicode string item per item type string.
A Unicode or binary string, in some cases with a file name (itself a Unicode string), as per the drag data item kind.
The drag data store item list is ordered in the order that the items were added to the list; most recently added last.
The following information, used to generate the UI feedback during the drag:
A drag data store mode, which is one of the following:
For the dragstart
event.
New data can be added to the drag data store.
For the drop
event. The list of
items representing dragged data can be read, including the data.
No new data can be added.
For all other events. The formats and kinds in the drag data store list of items representing dragged data can be enumerated, but the data itself is unavailable and no new data can be added.
A drag data store allowed effects state, which is a string.
When a drag data store is created, it must be initialized such that its
drag data store item list is empty, it has no
drag data store default feedback, its drag data
store elements list is empty, it has no drag data store
bitmap / drag data store hot spot coordinate,
its drag data store mode is protected mode, and its drag data
store allowed effects state is the string "uninitialized
".
DataTransfer
interfaceDataTransfer
objects are used to expose the
drag data store that underlies a drag-and-drop
operation.
interface DataTransfer {
attribute DOMString dropEffect;
attribute DOMString effectAllowed;
readonly attribute DataTransferItemList items;
void setDragImage(Element image, long x, long y);
void addElement(Element element);
/* old interface */
readonly attribute DOMString[] types;
DOMString getData(DOMString format);
void setData(DOMString format, DOMString data);
void clearData(optional DOMString format);
readonly attribute FileList files;
};
dropEffect
[ = value ]Returns the kind of operation that is currently selected. If
the kind of operation isn't one of those that is allowed by the
effectAllowed
attribute, then the operation will fail.
Can be set, to change the selected operation.
The possible values are "none
", "copy
", "link
", and "move
".
effectAllowed
[ = value ]Returns the kinds of operations that are to be allowed.
Can be set (during the dragstart
event), to change the
allowed operations.
The possible values are "none
", "copy
", "copyLink
", "copyMove
", "link
", "linkMove
", "move
", "all
", and "uninitialized
",
items
Returns a DataTransferItemList
object, with the drag data.
setDragImage
(element, x, y)Uses the given element to update the drag feedback, replacing any previously specified feedback.
addElement
(element)Adds the given element to the list of elements used to render the drag feedback.
types
Returns an array listing the formats that were set in the dragstart
event. In addition, if
any files are being dragged, then one of the types will be the
string "Files
".
getData
(format)Returns the specified data. If there is no such data, returns the empty string.
setData
(format, data)Adds the specified data.
clearData
( [ format ] )Removes the data of the specified formats. Removes all data if the argument is omitted.
files
Returns a FileList
of the files being dragged, if any.
DataTransfer
objects are used during the drag-and-drop events, and are only valid while
those events are being fired.
A DataTransfer
object is associated with a
drag data store while it is valid.
The dropEffect
attribute controls the drag-and-drop feedback that the user is given
during a drag-and-drop operation. When the DataTransfer
object is created, the dropEffect
attribute is
set to a string value. On getting, it must return its current value.
On setting, if the new value is one of "none
",
"copy
", "link
", or
"move
", then the attribute's current value
must be set to the new value. Other values must be ignored.
The effectAllowed
attribute is used in the drag-and-drop processing model to
initialize the dropEffect
attribute
during the dragenter
and dragover
events. When the
DataTransfer
object is created, the effectAllowed
attribute is set to a string value. On getting, it must return its
current value. On setting, if drag data store's mode is the read/write mode and the new value is
one of "none
", "copy
",
"copyLink
", "copyMove
",
"link
", "linkMove
",
"move
", "all
", or "uninitialized
", then the attribute's current value
must be set to the new value. Otherwise it must be left
unchanged.
The items
attribute must return a DataTransferItemList
object
associated with the DataTransfer
object. The same
object must be returned each time.
The setDragImage(element, x, y)
method must run the following
steps:
If the DataTransfer
object is no longer
associated with a drag data store, abort these steps.
Nothing happens.
If the drag data store's mode is not the read/write mode, abort these steps. Nothing happens.
If the element argument is an
img
element, then set the drag data store
bitmap to the element's image (at its intrinsic size);
otherwise, set the drag data store bitmap to an image
generated from the given element (the exact mechanism for doing so
is not currently specified).
Set the drag data store hot spot coordinate to the given x, y coordinate.
The addElement(element)
method is an alternative way of
specifying how the user agent is to render the drag feedback. The method
must run the following steps:
If the DataTransfer
object is no longer
associated with a drag data store, abort these steps.
Nothing happens.
If the drag data store's mode is not in the read/write mode, abort these steps. Nothing happens.
Add the given element to the element's drag data store elements list.
The difference between setDragImage()
and
addElement()
is
that the latter automatically generates the image based on the
current rendering of the elements added (potentially keeping it
updated as the drag continues, e.g. if the elements include an
actively playing video), whereas the former uses the exact specified
image at the time the method is invoked.
The types
attribute must return a live read only array giving the
strings that the following steps would produce. The same object must
be returned each time.
Start with an empty list L.
If the DataTransfer
object is no longer
associated with a drag data store, the array is empty.
Abort these steps; return the empty list L.
For each item in the drag data store item list whose kind is Plain Unicode string, add an entry to the list L consisting of the item's type string.
If there are any items in the drag data store item
list whose kind
is File, then add an entry to the list L
consisting of the string "Files
". (This value
can be distinguished from the other values because it is not
lowercase.)
The strings produced by these steps are those in the list L.
The getData(format)
method
must run the following steps:
If the DataTransfer
object is no longer
associated with a drag data store, return the empty
string and abort these steps.
If the drag data store's mode is the protected mode, return the empty string and abort these steps.
Let format be the first argument, converted to ASCII lowercase.
Let convert-to-URL be false.
If format equals "text
", change it to "text/plain
".
If format equals "url
", change it to "text/uri-list
" and set convert-to-URL to true.
If there is no item in the drag data store item list whose kind is Plain Unicode string and whose type string is equal to format, return the empty string and abort these steps.
Let result be the data of the item in the drag data store item list whose kind is Plain Unicode string and whose type string is equal to format.
If convert-to-URL is true, then parse
result as appropriate for text/uri-list
data, and then set result to the first URL from the list, if any, or
the empty string otherwise. [RFC2483]
Return result.
The setData(format, data)
method
must run the following steps:
If the DataTransfer
object is no longer
associated with a drag data store, abort these steps.
Nothing happens.
If the drag data store's mode is not the read/write mode, abort these steps. Nothing happens.
Let format be the first argument, converted to ASCII lowercase.
If format equals "text
", change it to "text/plain
".
If format equals "url
", change it to "text/uri-list
".
Remove the item in the drag data store item list whose kind is Plain Unicode string and whose type string is equal to format, if there is one.
Add an item to the drag data store item list whose kind is Plain Unicode string, whose type string is equal to format, and whose data is the string given by the method's second argument.
The clearData()
method must run the following steps:
If the DataTransfer
object is no longer
associated with a drag data store, abort these steps.
Nothing happens.
If the drag data store's mode is not the read/write mode, abort these steps. Nothing happens.
If the method was called with no arguments, remove each item in the drag data store item list whose kind is Plain Unicode string, and abort these steps.
Let format be the first argument, converted to ASCII lowercase.
If format equals "text
", change it to "text/plain
".
If format equals "url
", change it to "text/uri-list
".
Remove the item in the drag data store item list whose kind is Plain Unicode string and whose type string is equal to format, if there is one.
The clearData()
method does
not affect whether any files were included in the drag, so the types
attribute's list might
still not be empty after calling clearData()
(it would
still contain the "Files
" string if any files
were included in the drag).
The files
attribute must return a live FileList
sequence consisting of File
objects representing the
files found by the following steps. The same object must be returned
each time. Furthermore, for a given FileList
object and
a given underlying file, the same File
object must be
used each time.
Start with an empty list L.
If the DataTransfer
object is no longer
associated with a drag data store, the
FileList
is empty. Abort these steps; return the
empty list L.
If the drag data store's mode is the protected mode, abort these steps; return the empty list L.
For each item in the drag data store item list whose kind is File , add the item's data (the file, in particular its name and contents, as well as its type) to the list L.
The files found by these steps are those in the list L.
This version of the API does not expose the types of the files during the drag.
DataTransferItemList
interfaceEach DataTransfer
object is associated with a
DataTransferItemList
object.
interface DataTransferItemList { readonly attribute unsigned long length; getter DataTransferItem (unsigned long index); deleter void (unsigned long index); void clear(); DataTransferItem? add(DOMString data, DOMString type); DataTransferItem? add(File data); };
length
Returns the number of items in the drag data store.
Returns the DataTransferItem
object representing the indexth entry in the drag data store.
delete
items[index]Removes the indexth entry in the drag data store.
clear
()Removes all the entries in the drag data store.
add
(data)add
(data, type)Adds a new entry for the given data to the drag data store. If the data is plain text then a type string has to be provided also.
While the DataTransferItemList
object's
DataTransfer
object is associated with a drag
data store, the DataTransferItemList
object's
mode is the same as the drag data store mode.
When the DataTransferItemList
object's
DataTransfer
object is not associated with a
drag data store, the DataTransferItemList
object's mode is the disabled mode. The drag
data store referenced in this section (which is used only
when the DataTransferItemList
object is not in the
disabled mode) is the drag data store with which
the DataTransferItemList
object's
DataTransfer
object is associated.
The length
attribute must return zero if the object is in the disabled
mode; otherwise it must return the number of items in the
drag data store item list.
When a DataTransferItemList
object is not in the
disabled mode, its supported property indices
are the numbers in the range
0 .. n-1,
where n is the number of items in the drag
data store item list.
To determine the value of
an indexed property i of a
DataTransferItemList
object, the user agent must return a
DataTransferItem
object representing the ith item in the drag data store. The
same object must be returned each time a particular item is obtained
from this DataTransferItemList
object. The
DataTransferItem
object must be associated with the
same DataTransfer
object as the
DataTransferItemList
object when it is first created.
To delete an
existing indexed property i of a
DataTransferItemList
object, the user agent must run these
steps:
If the DataTransferItemList
object is not in the
read/write mode, throw an
InvalidStateError
exception and abort these
steps.
Remove the ith item from the drag data store.
The clear
method,
if the DataTransferItemList
object is in the read/write mode, must remove all the
items from the drag data store. Otherwise, it must do
nothing.
The add()
method
must run the following steps:
If the DataTransferItemList
object is not in the
read/write mode, return null and
abort these steps.
Jump to the appropriate set of steps from the following list:
If there is already an item in the drag data store item
list whose kind is Plain Unicode string and whose type string is
equal to the value of the method's second argument,
converted to ASCII lowercase, then throw a
NotSupportedError
exception and abort these
steps.
Otherwise, add an item to the drag data store item list whose kind is Plain Unicode string, whose type string is equal to the value of the method's second argument, converted to ASCII lowercase, and whose data is the string given by the method's first argument.
File
Add an item to the drag data store item list
whose kind is
File, whose type string is the type
of the File
,
converted to ASCII lowercase, and whose data is the
same as the File
's data.
Determine the value
of the indexed property corresponding to the newly added
item, and return that value (a newly created
DataTransferItem
object).
DataTransferItem
interfaceEach DataTransferItem
object is associated with a
DataTransfer
object.
interface DataTransferItem {
readonly attribute DOMString kind;
readonly attribute DOMString type;
void getAsString(FunctionStringCallback? _callback);
File? getAsFile();
};
[Callback, NoInterfaceObject]
interface FunctionStringCallback {
void handleEvent(DOMString data);
};
kind
Returns the drag data item kind, one of: "string", "file".
type
Returns the drag data item type string.
getAsString
(callback)Invokes the callback with the string data as the argument, if the drag data item kind is Plain Unicode string.
getAsFile
()Returns a File
object, if the drag data item kind is File.
While the DataTransferItem
object's
DataTransfer
object is associated with a drag
data store and that drag data store's drag
data store item list still contains the item that the
DataTransferItem
object represents, the
DataTransferItem
object's mode is the same as
the drag data store mode. When the
DataTransferItem
object's DataTransfer
object is not associated with a drag data
store, or if the item that the DataTransferItem
object represents has been removed from the relevant drag data
store item list, the DataTransferItem
object's
mode is the disabled mode. The drag data
store referenced in this section (which is used only when the
DataTransferItem
object is not in the disabled
mode) is the drag data store with which the
DataTransferItem
object's DataTransfer
object is associated.
The kind
attribute
must return the empty string if the DataTransferItem
object is in the disabled mode; otherwise it must return the
string given in the cell from the second column of the following
table from the row whose cell in the first column contains the
drag data item kind of the item represented by the
DataTransferItem
object:
Kind | String |
---|---|
Plain Unicode string | "string "
|
File | "file "
|
The type
attribute
must return the empty string if the DataTransferItem
object is in the disabled mode; otherwise it must return
the drag data item type string of the item represented
by the DataTransferItem
object.
The getAsString(callback)
method must run the following
steps:
If the callback is null, abort these steps.
If the DataTransferItem
object is not in the read/write mode or the read-only mode, abort these steps. The
callback is never invoked.
If the drag data item kind is not Plain Unicode string, abort these steps. The callback is never invoked.
Otherwise, queue a task to invoke callback, passing the actual data of the item
represented by the DataTransferItem
object as the
argument.
The getAsFile()
method must run the following steps:
If the DataTransferItem
object is not in the read/write mode or the read-only mode, return null and abort
these steps.
If the drag data item kind is not File, then return null and abort these steps.
Return a new File
object representing the
actual data of the item represented by the
DataTransferItem
object.
DragEvent
interfaceThe drag-and-drop processing model involves several events. They
all use the DragEvent
interface.
[Constructor(DOMString type, optional DragEventInit eventInitDict)] interface DragEvent : MouseEvent { readonly attribute DataTransfer? dataTransfer; }; dictionary DragEventInit : MouseEventInit { DataTransfer? dataTransfer; };
dataTransfer
Returns the DataTransfer
object for the event.
The dataTransfer
attribute of the DragEvent
interface must return the
value it was initialized to. When the object is created, this
attribute must be initialized to null. It represents the context
information for the event.
When a user agent is required to fire a DND event named e at an element, using a particular drag data store, the user agent must run the following steps:
If e is dragstart
, set the drag data
store mode to the read/write
mode.
If e is drop
, set the drag data store
mode to the read-only
mode.
Let dataTransfer be a newly created
DataTransfer
object associated with the given
drag data store.
Set the effectAllowed
attribute to the drag data store's drag data
store allowed effects state.
Set the dropEffect
attribute to
"none
" if e is dragstart
, drag
, or dragleave
; to the value
corresponding to the current drag operation if e is drop
or dragend
; and to a value based on the
effectAllowed
attribute's value and to the drag-and-drop source, as given by the
following table, otherwise (i.e. if e is dragenter
or dragover
):
effectAllowed |
dropEffect |
---|---|
"none " |
"none " |
"copy " |
"copy " |
"copyLink " |
"copy ", or, if appropriate, "link " |
"copyMove " |
"copy ", or, if appropriate, "move " |
"all " |
"copy ", or, if appropriate, either "link " or "move " |
"link " |
"link " |
"linkMove " |
"link ", or, if appropriate, "move " |
"move " |
"move " |
"uninitialized " when what is being dragged is a selection from a text field |
"move ", or, if appropriate, either "copy " or "link " |
"uninitialized " when what is being dragged is a selection |
"copy ", or, if appropriate, either "link " or "move " |
"uninitialized " when what is being dragged is an a element with an href attribute |
"link ", or, if appropriate, either "copy " or "move " |
Any other case | "copy ", or, if appropriate, either "link " or "move " |
Where the table above provides possibly appropriate alternatives, user agents may instead use the listed alternative values if platform conventions dictate that the user has requested those alternate effects.
For example, Windows platform conventions are
such that dragging while holding the "alt" key indicates a
preference for linking the data, rather than moving or copying it.
Therefore, on a Windows system, if "link
" is
an option according to the table above while the "alt" key is
depressed, the user agent could select that instead of "copy
" or "move
.
Create a DragEvent
object and initialize it to
have the given name e, to bubble, to be
cancelable unless e is dragleave
or dragend
, and to have the detail
attribute initialized to
zero, the mouse and key attributes initialized according to the
state of the input devices as they would be for user interaction
events, the relatedTarget
attribute
initialized to null, and the dataTransfer
attribute
initialized to dataTransfer, the
DataTransfer
object created above.
If there is no relevant pointing device, the object must have
its screenX
, screenY
,
clientX
, clientY
, and
button
attributes set to 0.
Dispatch the newly created DragEvent
object at
the specified target element.
Set the drag data store allowed effects state
to the current value of dataTransfer's effectAllowed
attribute. (It can only have changed value if e
is dragstart
.)
Set the drag data store mode back to the protected mode if it was changed in the first step.
Break the association between dataTransfer and the drag data store.
When the user attempts to begin a drag operation, the user agent must run the following steps. User agents must act as if these steps were run even if the drag actually started in another document or application and the user agent was not aware that the drag was occuring until it intersected with a document under the user agent's purview.
Determine what is being dragged, as follows:
If the drag operation was invoked on a selection, then it is the selection that is being dragged.
Otherwise, if the drag operation was invoked on a
Document
, it is the first element, going up the
ancestor chain, starting at the node that the user tried to drag,
that has the IDL attribute draggable
set to true. If there is no
such element, then nothing is being dragged; abort these steps,
the drag-and-drop operation is never started.
Otherwise, the drag operation was invoked outside the user agent's purview. What is being dragged is defined by the document or application where the drag was started.
img
elements and a
elements with an href
attribute have their draggable
attribute set to true by default.
Create a drag data store. All the DND events fired subsequently by the steps in this section must use this drag data store.
Establish which DOM node is the source node, as follows:
If it is a selection that is being dragged, then the
source node is the Text
node that the
user started the drag on (typically the Text
node
that the user originally clicked). If the user did not specify a
particular node, for example if the user just told the user agent
to begin a drag of "the selection", then the source
node is the first Text
node containing a part
of the selection.
Otherwise, if it is an element that is being dragged, then the source node is the element that is being dragged.
Otherwise, the source node is part of another document or application. When this specification requires that an event be dispatched at the source node in this case, the user agent must instead follow the platform-specific conventions relevant to that situation.
Multiple events are fired on the source node during the course of the drag-and-drop operation.
Determine the list of dragged nodes, as follows:
If it is a selection that is being dragged, then the list of dragged nodes contains, in tree order, every node that is partially or completely included in the selection (including all their ancestors).
Otherwise, the list of dragged nodes contains only the source node, if any.
If it is a selection that is being dragged, then add an item to the drag data store item list, with its properties set as follows:
text/plain
"Otherwise, if any files are being dragged, then add one item per file to the drag data store item list, with their properties set as follows:
application/octet-stream
" otherwise.Dragging files can currently only happen from outside a browsing context, for example from a file system manager application.
If the drag initiated outside of the application, the user agent must add items to the drag data store item list as appropriate for the data being dragged, honoring platform conventions where appropriate; however, if the platform conventions do not use MIME types to label dragged data, the user agent must make a best-effort attempt to map the types to MIME types, and, in any case, all the drag data item type strings must be converted to ASCII lowercase.
User agents may also add one or more items representing the selection or dragged element(s) in other forms, e.g. as HTML.
If the list of dragged nodes is not empty, then extract the microdata from those nodes into a JSON form, and add one item to the drag data store item list, with its properties set as follows:
application/microdata+json
Run the following substeps:
Let urls be an empty list of absolute URLs.
For each node in the list of dragged nodes:
If urls is still empty, abort these substeps.
Let url string be the result of concatenating the strings in urls, in the order they were added, separated by a U+000D CARRIAGE RETURN U+000A LINE FEED character pair (CRLF).
Add one item to the drag data store item list, with its properties set as follows:
text/uri-list
If it is an element that is being dragged, then set the drag data store elements list to contain just the source node.
Otherwise, update the drag data store default feedback as appropriate for the user agent (if the user is dragging the selection, then the selection would likely be the basis for this feedback; if the drag began outside the user agent, then the platform conventions for determining the drag feedback should be used).
Script can use the addElement()
method to
add further elements to the list of what is being dragged. (This
list is only used for rendering the drag feedback.)
Fire a DND event named dragstart
at the source
node.
If the event is canceled, then the drag-and-drop operation should not occur; abort these steps.
Since events with no event listeners registered are, almost by definition, never canceled, drag-and-drop is always available to the user if the author does not specifically prevent it.
Initiate the drag-and-drop operation in a manner consistent with platform conventions, and as described below.
The drag-and-drop feedback must be generated from the first of the following sources that is available:
From the moment that the user agent is to initiate the drag-and-drop operation, until the end of the drag-and-drop operation, device input events (e.g. mouse and keyboard events) must be suppressed.
During the drag operation, the element directly indicated by the user as the drop target is called the immediate user selection. (Only elements can be selected by the user; other nodes must not be made available as drop targets.) However, the immediate user selection is not necessarily the current target element, which is the element currently selected for the drop part of the drag-and-drop operation.
The immediate user selection changes as the user selects different elements (either by pointing at them with a pointing device, or by selecting them in some other way). The current target element changes when the immediate user selection changes, based on the results of event listeners in the document, as described below.
Both the current target element and the immediate user selection can be null, which means no target element is selected. They can also both be elements in other (DOM-based) documents, or other (non-Web) programs altogether. (For example, a user could drag text to a word-processor.) The current target element is initially null.
In addition, there is also a current drag operation,
which can take on the values "none
", "copy
", "link
", and "move
". Initially, it has the value "none
". It is updated by the user agent as described
in the steps below.
User agents must, as soon as the drag operation is initiated and every 350ms (±200ms) thereafter for as long as the drag operation is ongoing, queue a task to perform the following steps in sequence:
If the user agent is still performing the previous iteration of the sequence (if any) when the next iteration becomes due, abort these steps for this iteration (effectively "skipping missed frames" of the drag-and-drop operation).
Fire a DND event named drag
event at the source
node. If this event is canceled, the user agent must set
the current drag operation to "none
" (no drag operation).
If the drag
event was not
canceled and the user has not ended the drag-and-drop operation,
check the state of the drag-and-drop operation, as follows:
If the user is indicating a different immediate user selection than during the last iteration (or if this is the first iteration), and if this immediate user selection is not the same as the current target element, then update the current target element as follows:
Set the current target element to null also.
Set the current target element to the immediate user selection.
Fire a DND event named dragenter
at the
immediate user selection.
If the event is canceled, then set the current target element to the immediate user selection.
Otherwise, run the appropriate step from the following list:
textarea
, or an input
element whose type
attribute is in the Text state) or an
editing host or editable element,
and the drag data store item list has an item
with the drag data item type string
"text/plain
" and the drag data item
kind Plain Unicode stringSet the current target element to the immediate user selection anyway.
dropzone
attribute
that matches the
drag data storeSet the current target element to the immediate user selection anyway.
dropzone
attribute that matches the drag
data storeLet new target be the nearest (deepest) such ancestor element.
If the current target element is new target, then leave the current target element unchanged.
Otherwise, fire a DND event named dragenter
at new target. Then, set the current
target element to new target,
regardless of whether that event was canceled or not.
Leave the current target element unchanged.
Fire a DND event named dragenter
at the body
element, if there is one, or at the
Document
object, if not. Then, set the
current target element to the body
element, regardless of whether that event was
canceled or not.
If the previous step caused the current target
element to change, and if the previous target element was
not null or a part of a non-DOM document, then fire a DND
event named dragleave
at the previous target
element.
If the current target element is a DOM element,
then fire a DND event named dragover
at this current
target element.
If the dragover
event is
not canceled, run the appropriate step from the following
list:
textarea
, or an input
element
whose type
attribute is in
the Text state) or an
editing host or editable element, and
the drag data store item list has an item with
the drag data item type string
"text/plain
" and the drag data item
kind Plain Unicode stringSet the current drag operation to either
"copy
" or "move
",
as appropriate given the platform conventions.
dropzone
attribute
that matches the
drag data store and specifies an
operationSet the current drag operation to the
operation specified by the
dropzone
attribute of the
current target element.
dropzone
attribute
that matches the
drag data store and does not specify an
operationSet the current drag operation to "copy
".
Reset the current drag operation to "none
".
Otherwise (if the dragover
event is
canceled), set the current drag operation based on
the values of the effectAllowed
and
dropEffect
attributes of the DragEvent
object's dataTransfer
object as
they stood after the event dispatch finished, as per the
following table:
effectAllowed |
dropEffect |
Drag operation |
---|---|---|
"uninitialized ", "copy ", "copyLink ", "copyMove ", or "all " |
"copy " |
"copy " |
"uninitialized ", "link ", "copyLink ", "linkMove ", or "all " |
"link " |
"link " |
"uninitialized ", "move ", "copyMove ", "linkMove ", or "all " |
"move " |
"move " |
Any other case | "none " |
Otherwise, if the current target element is not a DOM element, use platform-specific mechanisms to determine what drag operation is being performed (none, copy, link, or move), and set the current drag operation accordingly.
Update the drag feedback (e.g. the mouse cursor) to match the current drag operation, as follows:
Drag operation | Feedback |
---|---|
"copy " |
Data will be copied if dropped here. |
"link " |
Data will be linked if dropped here. |
"move " |
Data will be moved if dropped here. |
"none " |
No operation allowed, dropping here will cancel the drag-and-drop operation. |
Otherwise, if the user ended the drag-and-drop operation (e.g.
by releasing the mouse button in a mouse-driven drag-and-drop
interface), or if the drag
event
was canceled, then this will be the last iteration. Run the
following steps, then stop the drag-and-drop operation:
If the current drag operation is "none
" (no drag operation), or, if the user ended
the drag-and-drop operation by canceling it (e.g. by hitting the
Escape key), or if the current target
element is null, then the drag operation failed. Run
these substeps:
Let dropped be false.
If the current target element is a DOM
element, fire a DND event named dragleave
at it; otherwise, if
it is not null, use platform-specific conventions for drag
cancellation.
Otherwise, the drag operation might be a success; run these substeps:
Let dropped be true.
If the current target element is a DOM
element, fire a DND event named drop
at it; otherwise, use
platform-specific conventions for indicating a drop.
If the event is canceled, set the current drag
operation to the value of the dropEffect
attribute
of the DragEvent
object's dataTransfer
object
as it stood after the event dispatch finished.
Otherwise, the event is not canceled; perform the event's default action, which depends on the exact target as follows:
textarea
, or an input
element whose type
attribute is in the Text state) or an
editing host or editable element,
and the drag data store item list has an item
with the drag data item type string
"text/plain
" and the drag data item
kind Plain Unicode stringInsert the actual data of the first item in the
drag data store item list to have a drag data item type
string of "text/plain
" and a drag data item kind
that is Plain Unicode string into the text field or
editing host or editable element in
a manner consistent with platform-specific conventions (e.g.
inserting it at the current mouse cursor position, or
inserting it at the end of the field).
Reset the current drag operation to
"none
".
Fire a DND event named dragend
at the source
node.
Run the appropriate steps from the following list as the
default action of the dragend
event:
move
", and the source of the drag-and-drop
operation is a selection in the DOM that is entirely contained
within an editing hostmove
", and the source of the drag-and-drop
operation is a selection in a text fieldThe user agent should delete the dragged selection from the relevant text field.
none
"The drag was canceled. If the platform conventions dictate that this be represented to the user (e.g. by animating the dragged selection going back to the source of the drag-and-drop operation), then do so.
The event has no default action.
For the purposes of this step, a text field is a
textarea
element or an input
element
whose type
attribute is in
one of the
Text,
Search,
Tel,
URL,
E-mail,
Password, or
Number
states.
User agents are encouraged to consider how to react to drags near the edge of scrollable regions. For example, if a user drags a link to the bottom of the viewport on a long page, it might make sense to scroll the page so that the user can drop the link lower on the page.
This model is independent of which
Document
object the nodes involved are from; the events
are fired as described above and the rest of the processing model
runs as described above, irrespective of how many documents are
involved in the operation.
This section is non-normative.
The following events are involved in the drag-and-drop model.
Event Name | Target | Cancelable? | Drag data store mode | dropEffect |
Default Action |
---|---|---|---|---|---|
dragstart |
Source node | ✓ Cancelable | Read/write mode | "none " |
Initiate the drag-and-drop operation |
drag |
Source node | ✓ Cancelable | Protected mode | "none " |
Continue the drag-and-drop operation |
dragenter |
Immediate user selection or the body element | ✓ Cancelable | Protected mode | Based on effectAllowed value |
Reject immediate user selection as potential target element |
dragleave |
Previous target element | — | Protected mode | "none " |
None |
dragover |
Current target element | ✓ Cancelable | Protected mode | Based on effectAllowed value |
Reset the current drag operation to "none" |
drop |
Current target element | ✓ Cancelable | Read-only mode | Current drag operation | Varies |
dragend |
Source node | — | Protected mode | Current drag operation | Varies |
Not shown in the above table: all these events bubble, and the
effectAllowed
attribute always has the value it had after the dragstart
event, defaulting to "uninitialized
" in the dragstart
event.
draggable
attributeAll HTML elements may have the draggable
content attribute set. The
draggable
attribute is an
enumerated attribute. It has three states. The first
state is true and it has the keyword true
. The second state is false and it has
the keyword false
. The third state is
auto; it has no keywords but it is the missing value
default.
The true state means the element is draggable; the false state means that it is not. The auto state uses the default behavior of the user agent.
draggable
[ = value ]Returns true if the element is draggable; otherwise, returns false.
Can be set, to override the default and set the draggable
content attribute.
The draggable
IDL
attribute, whose value depends on the content attribute's in the way
described below, controls whether or not the element is
draggable. Generally, only text selections are draggable, but
elements whose draggable
IDL
attribute is true become draggable as well.
If an element's draggable
content attribute has the state true, the draggable
IDL attribute must return
true.
Otherwise, if the element's draggable
content attribute has the
state false, the draggable
IDL attribute must return
false.
Otherwise, the element's draggable
content attribute has the
state auto. If the element is an img
element,
or, if the element is an a
element with an href
content attribute, the draggable
IDL attribute must return
true.
Otherwise, the draggable
DOM
must return false.
If the draggable
IDL attribute
is set to the value false, the draggable
content attribute must be
set to the literal value false
. If the draggable
IDL attribute is set to the
value true, the draggable
content attribute must be set to the literal value true
.
dropzone
attributeAll HTML elements may have the dropzone
content attribute set. When
specified, its value must be an unordered set of unique
space-separated tokens that are ASCII
case-insensitive. The allowed values are the following:
copy
Indicates that dropping an accepted item on the element will result in a copy of the dragged data.
move
Indicates that dropping an accepted item on the element will result in the dragged data being moved to the new location.
link
Indicates that dropping an accepted item on the element will result in a link to the original data.
string:
"Indicates that items with the drag data item kind Plain Unicode string and the drag data item type string set to a value that matches the remainder of the keyword are accepted.
file:
"Indicates that items with the drag data item kind File and the drag data item type string set to a value that matches the remainder of the keyword are accepted.
The dropzone
content
attribute's values must not have more than one of the three feedback
values (copy
, move
, and link
) specified. If none are
specified, the copy
value is
implied.
A dropzone
attribute matches a drag data store if
the dropzone
processing
steps result in a match.
A dropzone
attribute specifies an operation if
the dropzone
processing
steps result in a specified operation. The specified
operation is as given by those steps.
The dropzone
processing
steps are as follows. They either result in a match or not,
and separate from this result either in a specified operation or
not, as defined below.
Let value be the value of the dropzone
attribute.
Let keywords be the result of splitting value on spaces.
Let matched be false.
Let operation be unspecified.
For each value in keywords, if any, in the order that they were found in value, run the following steps.
Let keyword be the keyword.
If keyword is one of "copy
", "move
", or "link
", then: run the following
substeps:
If operation is still unspecified, then let operation be the string given by keyword.
Skip to the step labeled end of keyword below.
If keyword does not contain a U+003A COLON character (:), or if the first such character in keyword is either the first character or the last character in the string, then skip to the step labeled end of keyword below.
Let kind code be the substring of keyword from the first character in the string to the last character in the string that is before the first U+003A COLON character (:) in the string, converted to ASCII lowercase.
Jump to the appropriate step from the list below, based on the value of kind code:
string
"Let kind be Plain Unicode string.
file
"Let kind be File.
Skip to the step labeled end of keyword below.
Let type be the substring of keyword from the first character after the first U+003A COLON character (:) in the string, to the last character in the string, converted to ASCII lowercase.
If there exist any items in the drag data store item list whose drag data item kind is the kind given in kind and whose drag data item type is type, then let matched be true.
End of keyword: Go on to the next keyword, if any, or the next step in the overall algorithm, if there are no more.
The algorithm results in a match if matched is true, and does not otherwise.
The algorithm results in a specified operation if operation is not unspecified. The specified operation, if one is specified, is the one given by operation.
The dropzone
IDL
attribute must reflect the content attribute of the
same name.
In this example, a div
element is made into a drop
target for image files using the dropzone
attribute. Images dropped
into the target are then displayed.
<div dropzone="copy file:image/png file:image/gif file:image/jpeg" ondrop="receive(event, this)"> <p>Drop an image here to have it displayed.</p> </div> <script> function receive(event, element) { var data = event.dataTransfer.items; for (var i = 0; i < data.length; i += 1) { if ((data[i].kind == 'file') && (data[i].type.match('^image/'))) { var img = new Image(); img.src = window.createObjectURL(data[i].getAsFile()); element.appendChild(img); } } } </script>
User agents must not make the data added to the
DataTransfer
object during the dragstart
event available to scripts
until the drop
event, because
otherwise, if a user were to drag sensitive information from one
document to a second document, crossing a hostile third document in
the process, the hostile document could intercept the data.
For the same reason, user agents must consider a drop to be
successful only if the user specifically ended the drag operation
— if any scripts end the drag operation, it must be considered
unsuccessful (canceled) and the drop
event must not be fired.
User agents should take care to not start drag-and-drop operations in response to script actions. For example, in a mouse-and-window environment, if a script moves a window while the user has his mouse button depressed, the UA would not consider that to start a drag. This is important because otherwise UAs could cause data to be dragged from sensitive sources and dropped into hostile documents without the user's consent.
User agents should filter potentially active (scripted) content (e.g. HTML) when it is dragged and when it is dropped, using a whitelist of known-safe features. Similarly, relative URLs should be turned into absolute URLs to avoid references changing in unexpected ways. This specification does not specify how this is performed.
Consider a hostile page providing some content and getting the
user to select and drag and drop (or indeed, copy and paste) that
content to a victim page's contenteditable
region. If the
browser does not ensure that only safe content is dragged,
potentially unsafe content such as scripts and event handlers in
the selection, once dropped (or pasted) into the victim site, get
the privileges of the victim site. This would thus enable a
cross-site scripting attack.
This section is non-normative.
This specification defines an API for running scripts in the background independently of any user interface scripts.
This allows for long-running scripts that are not interrupted by scripts that respond to clicks or other user interactions, and allows long tasks to be executed without yielding to keep the page responsive.
Workers (as these background scripts are called herein) are relatively heavy-weight, and are not intended to be used in large numbers. For example, it would be inappropriate to launch one worker for each pixel of a four megapixel image. The examples below show some appropriate uses of workers.
Generally, workers are expected to be long-lived, have a high start-up performance cost, and a high per-instance memory cost.
This section is non-normative.
There are a variety of uses that workers can be put to. The following subsections show various examples of this use.
This section is non-normative.
The simplest use of workers is for performing a computationally expensive task without interrupting the user interface.
In this example, the main document spawns a worker to (naïvely) compute prime numbers, and progressively displays the most recently found prime number.
The main page is as follows:
EXAMPLE workers/primes/page.html
The Worker()
constructor call
creates a worker and returns a Worker
object
representing that worker, which is used to communicate with the
worker. That object's onmessage
event handler allows the code to receive messages from the worker.
The worker itself is as follows:
EXAMPLE workers/primes/worker.js
The bulk of this code is simply an unoptimized search for a prime
number. The postMessage()
method is used to send a message back to the page when a prime is
found.
This section is non-normative.
In this example, the main document uses two workers, one for fetching stock updates for at regular intervals, and one for fetching performing search queries that the user requests.
The main page is as follows:
EXAMPLE workers/stocks/page.html
The two workers use a common library for performing the actual network calls. This library is as follows:
EXAMPLE workers/stocks/io.js
The stock updater worker is as follows:
EXAMPLE workers/stocks/ticker.js
The search query worker is as follows:
EXAMPLE workers/stocks/searcher.js
This section is non-normative.
This section introduces shared workers using a Hello World example. Shared workers use slightly different APIs, since each worker can have multiple connections.
This first example shows how you connect to a worker and how a worker can send a message back to the page when it connects to it. Received messages are displayed in a log.
Here is the HTML page:
EXAMPLE workers/shared/001/test.html
Here is the JavaScript worker:
EXAMPLE workers/shared/001/test.js
This second example extends the first one by changing two things:
first, messages are received using addEventListener()
instead of an event handler IDL attribute, and
second, a message is sent to the worker, causing the worker
to send another message in return. Received messages are again
displayed in a log.
Here is the HTML page:
EXAMPLE workers/shared/002/test.html
Here is the JavaScript worker:
EXAMPLE workers/shared/002/test.js
Finally, the example is extended to show how two pages can
connect to the same worker; in this case, the second page is merely
in an iframe
on the first page, but the same principle
would apply to an entirely separate page in a separate
top-level browsing context.
Here is the outer HTML page:
EXAMPLE workers/shared/003/test.html
Here is the inner HTML page:
EXAMPLE workers/shared/003/inner.html
Here is the JavaScript worker:
EXAMPLE workers/shared/003/test.js
This section is non-normative.
In this example, multiple windows (viewers) can be opened that are all viewing the same map. All the windows share the same map information, with a single worker coordinating all the viewers. Each viewer can move around independently, but if they set any data on the map, all the viewers are updated.
The main page isn't interesting, it merely provides a way to open the viewers:
EXAMPLE workers/multiviewer/page.html
The viewer is more involved:
EXAMPLE workers/multiviewer/viewer.html
There are several key things worth noting about the way the viewer is written.
Multiple listeners. Instead of a single message processing function, the code here attaches multiple event listeners, each one performing a quick check to see if it is relevant for the message. In this example it doesn't make much difference, but if multiple authors wanted to collaborate using a single port to communicate with a worker, it would allow for independent code instead of changes having to all be made to a single event handling function.
Registering event listeners in this way also allows you to
unregister specific listeners when you are done with them, as is
done with the configure()
method in this
example.
Finally, the worker:
EXAMPLE workers/multiviewer/worker.js
Connecting to multiple pages. The script uses
the onconnect
event listener to listen for multiple connections.
Direct channels. When the worker receives a "msg" message from one viewer naming another viewer, it sets up a direct connection between the two, so that the two viewers can communicate directly without the worker having to proxy all the messages.
This section is non-normative.
With multicore CPUs becoming prevalent, one way to obtain better performance is to split computationally expensive tasks amongst multiple workers. In this example, a computationally expensive task that is to be performed for every number from 1 to 10,000,000 is farmed out to ten subworkers.
The main page is as follows, it just reports the result:
EXAMPLE workers/multicore/page.html
The worker itself is as follows:
EXAMPLE workers/multicore/worker.js
It consists of a loop to start the subworkers, and then a handler that waits for all the subworkers to respond.
The subworkers are implemented as follows:
EXAMPLE workers/multicore/core.js
They receive two numbers in two events, perform the computation for the range of numbers thus specified, and then report the result back to the parent.
This section is non-normative.
Creating a worker requires a URL to a JavaScript file. The Worker()
constructor is invoked with the
URL to that file as its only argument; a worker is then created and
returned:
var worker = new Worker('helper.js');
This section is non-normative.
Dedicated workers use MessagePort
objects behind the
scenes, and thus support all the same features, such as sending
structured data, transferring binary data, and transferring other
ports.
To receive messages from a dedicated worker, use the onmessage
event handler IDL attribute on the
Worker
object:
worker.onmessage = function (event) { ... };
You can also use the addEventListener()
method.
The implicit MessagePort
used by
dedicated workers has its port message queue implicitly
enabled when it is created, so there is no equivalent to the
MessagePort
interface's start()
method on the
Worker
interface.
To send data to a worker, use the postMessage()
method.
Structured data can be sent over this communication channel. To send
ArrayBuffer
objects efficiently (by transferring them
rather than cloning them), list them in an array in the second
argument.
worker.postMessage({ operation: 'find-edges', input: buffer, // an ArrayBuffer object threshold: 0.6, }, [buffer]);
To receive a message inside the worker, the onmessage
event handler IDL
attribute is used.
onmessage = function (event) { ... };
You can again also use the addEventListener()
method.
In either case, the data is provided in the event object's data
attribute.
To send messages back, you again use postMessage()
.
It supports the structured data in the same manner.
postMessage(event.data.input, [event.data.input]); // transfer the buffer back
This section is non-normative.
Shared workers are identified in one of two ways: either by the URL of the script used to create it, or by explicit name. When created by name, the URL used by the first page to create the worker with that name is the URL of the script that will be used for that worker. This allows multiple applications on a domain to all use a single shared worker to provide a common service, without the applications having to keep track of a common URL for the script used to provide the service.
In either case, shared workers are scoped by origin. Two different sites using the same names will not collide.
Creating shared workers is done using the SharedWorker()
constructor. This
constructor takes the URL to the script to use for its first
argument, and the name of the worker, if any, as the second
argument.
var worker = new SharedWorker('service.js');
Communicating with shared workers is done with explicit
MessagePort
objects. The object returned by the SharedWorker()
constructor holds a
reference to the port on its port
attribute.
worker.port.onmessage = function (event) { ... }; worker.port.postMessage('some message'); worker.port.postMessage({ foo: 'structured', bar: ['data', 'also', 'possible']});
Inside the shared worker, new clients of the worker are announced
using the connect
event. The port
for the new client is given by the event object's source
attribute.
onconnect = function (event) { var newPort = event.source; // set up a listener newPort.onmessage = function (event) { ... }; // send a message back to the port newPort.postMessage('ready!'); // can also send structured data, of course };
There are two kinds of workers; dedicated workers, and shared workers. Dedicated workers, once created, and are linked to their creator; but message ports can be used to communicate from a dedicated worker to multiple other browsing contexts or workers. Shared workers, on the other hand, are named, and once created any script running in the same origin can obtain a reference to that worker and communicate with it.
The global scope is the "inside" of a worker.
WorkerGlobalScope
common interfaceinterface WorkerGlobalScope : EventTarget { readonly attribute WorkerGlobalScope self; readonly attribute WorkerLocation location; void close(); attribute EventHandler onerror; attribute EventHandler onoffline; attribute EventHandler ononline; }; WorkerGlobalScope implements WorkerUtils;
The self
attribute
must return the WorkerGlobalScope
object itself.
The location
attribute must return the WorkerLocation
object created
for the WorkerGlobalScope
object when the worker was
created. It represents the absolute URL of the script
that was used to initialize the worker, after any redirects.
When a script invokes the close()
method on a WorkerGlobalScope
object, the user agent
must run the following steps (atomically):
Discard any tasks that have been added to the event loop's task queues.
Set the worker's WorkerGlobalScope
object's
closing flag to
true. (This prevents any further tasks from being queued.)
The following are the event handlers (and their
corresponding event handler
event types) that must be supported, as IDL attributes, by
objects implementing the WorkerGlobalScope
interface:
Event handler | Event handler event type |
---|---|
onerror | error
|
onoffline | offline
|
ononline | online
|
Each WorkerGlobalScope
object has a worker
origin that is set when the object is created.
For data:
URLs, this is the origin
of the entry script that called the constructor. For
other URLs, this is the origin
of the value of the absolute URL given in the worker's
attribute.
DedicatedWorkerGlobalScope
interfaceinterface DedicatedWorkerGlobalScope : WorkerGlobalScope { void postMessage(any message, optional sequence<Transferable> transfer); attribute EventHandler onmessage; };
The DedicatedWorkerGlobalScope
interface must only
be exposed if the JavaScript
global environment is a dedicated worker
environment.
DedicatedWorkerGlobalScope
objects act as if they
had an implicit MessagePort
associated with them. This
port is part of a channel that is set up when the worker is created,
but it is not exposed. This object must never be garbage collected
before the DedicatedWorkerGlobalScope
object.
All messages received by that port must immediately be retargeted
at the DedicatedWorkerGlobalScope
object.
The postMessage()
method on
DedicatedWorkerGlobalScope
objects must act as if, when
invoked, it immediately invoked the
method of the same name on the port, with the same arguments, and
returned the same return value.
The following are the event handlers (and their
corresponding event handler
event types) that must be supported, as IDL attributes, by
objects implementing the DedicatedWorkerGlobalScope
interface:
Event handler | Event handler event type |
---|---|
onmessage | message
|
For the purposes of the application cache networking model, a dedicated worker is an extension of the cache host from which it was created.
SharedWorkerGlobalScope
interfaceinterface SharedWorkerGlobalScope : WorkerGlobalScope { readonly attribute DOMString name; readonly attribute ApplicationCache applicationCache; attribute EventHandler onconnect; };
The SharedWorkerGlobalScope
interface must only be
exposed if the JavaScript global
environment is a shared worker environment.
Shared workers receive message ports through connect
events on
their global object for each connection.
The name
attribute must return the value it was assigned when the
SharedWorkerGlobalScope
object was created by the
"run a worker" algorithm. Its value represents the name
that can be used to obtain a reference to the worker using the
SharedWorker
constructor.
The following are the event handlers (and their
corresponding event handler
event types) that must be supported, as IDL attributes, by
objects implementing the SharedWorkerGlobalScope
interface:
Event handler | Event handler event type |
---|---|
onconnect | connect
|
For the purposes of the application cache networking model, a shared worker is its own cache host. The run a worker algorithm takes care of associating the worker with an application cache.
The applicationCache
attribute returns the ApplicationCache
object for the
worker.
Each WorkerGlobalScope
object has an event
loop distinct from those defined for units of related
similar-origin browsing contexts. This event
loop has no associated browsing context, and its
task queues only have events,
callbacks, and networking activity as tasks. The processing model of these
event loops is defined below in the
run a worker algorithm.
Each WorkerGlobalScope
object also has a closing flag, which must
initially be false, but which can get set to true by the algorithms
in the processing model section below.
Once the WorkerGlobalScope
's closing flag is set to
true, the event loop's task
queues must discard any further tasks that would be added to them (tasks
already on the queue are unaffected except where otherwise
specified). Effectively, once the closing flag is true,
timers stop firing, notifications for all pending asynchronous
operations are dropped, etc.
Workers communicate with other workers and with browsing contexts through message channels and their
MessagePort
objects.
Each WorkerGlobalScope
worker global
scope has a list of the worker's ports, which
consists of all the MessagePort
objects that are
entangled with another port and that have one (but only one) port
owned by worker global scope. This list includes
the implicit
MessagePort
in the case of dedicated workers.
Each WorkerGlobalScope
also has a list of the
worker's workers. Initially this list is empty; it is
populated when the worker creates or obtains further workers.
Finally, each WorkerGlobalScope
also has a list of
the worker's Document
s. Initially this list
is empty; it is populated when the worker is created.
Whenever a Document
d is added to the
worker's Document
s, the user agent must, for each
worker q in the list of the worker's
workers whose list of the worker's
Document
s does not contain d, add d to q's
WorkerGlobalScope
owner's list of the worker's
Document
s.
Whenever a Document
object is discarded, it must be removed from the list of
the worker's Document
s of each worker
whose list contains that Document
.
Given a script's global object o
when creating or obtaining a worker, the list of relevant
Document
objects to add depends on the type of
o. If o is a
WorkerGlobalScope
object (i.e. if we are creating a
nested worker), then the relevant Document
s are the
Document
s that are in o's own list
of the worker's Document
s. Otherwise, o is a Window
object, and the relevant
Document
is just the Document
that is the
active document of the Window
object o.
A worker is said to be a permissible worker if its
list of the worker's Document
s is not
empty.
A worker is said to be a protected worker if it is a
permissible worker and either it has outstanding
timers, database transactions, or network connections, or its list
of the worker's ports is not empty, or its
WorkerGlobalScope
is actually a
SharedWorkerGlobalScope
object (i.e. the worker is a
shared worker).
A worker is said to be an active needed worker if any
of the Document
objects in the worker's
Document
s are fully active.
A worker is said to be a suspendable worker if it is not an active needed worker but it is a permissible worker.
When a user agent is to run a worker for a script with
URL url, a browsing
context owner browsing context, a
Document
owner document, an
origin owner origin, and with
global scope worker global scope, it must run
the following steps:
Create a separate parallel execution environment (i.e. a separate thread or process or equivalent construct), and run the rest of these steps asynchronously in that context.
If worker global scope is actually a
SharedWorkerGlobalScope
object (i.e. the worker is a
shared worker), and there are any relevant application caches that are identified by a
manifest URL with the same origin as url and that have url as one of
their entries, not excluding entries marked as foreign, then associate the
worker global scope with the most appropriate application
cache of those that match.
Attempt to fetch the resource identified by url, from the owner origin, with the synchronous flag set and the force same-origin flag set.
If the attempt fails, then for each Worker
or
SharedWorker
object associated with worker global scope, queue a task to
fire a simple event named error
at that object. Abort these
steps.
If the attempt succeeds, then let source be the script resource decoded as UTF-8, with error handling.
Let language be JavaScript.
As with script
elements, the MIME
type of the script is ignored. Unlike with script
elements, there is no way to override the type. It's always
assumed to be JavaScript.
In the newly created execution environment, create a
JavaScript global environment whose global
object is worker global scope. If worker global scope is a
DedicatedWorkerGlobalScope
object, then this is a
dedicated worker environment. Otherwise, worker global scope is a
SharedWorkerGlobalScope
object, and this is a
shared worker environment. (In either case, by
definition, it is a worker environment.)
A new script is now created, as follows.
Create a new script execution environment set up as appropriate for the scripting language language.
Parse/compile/initialize source using that script execution environment, as appropriate for language, and thus obtain a list of code entry-points; set the initial code entry-point to the entry-point for any executable code to be immediately run.
Set the script's global object to worker global scope.
Set the script's browsing context to owner browsing context.
Set the script's document to owner document.
Set the script's URL character encoding to UTF-8. (This is just used for encoding non-ASCII characters in the query component of URLs.)
Set the script's base URL to url.
Closing orphan workers: Start monitoring the worker such that no sooner than it stops being either a protected worker or a suspendable worker, and no later than it stops being a permissible worker, worker global scope's closing flag is set to true.
Suspending workers: Start monitoring the worker, such that whenever worker global scope's closing flag is false and the worker is a suspendable worker, the user agent suspends execution of script in that worker until such time as either the closing flag switches to true or the worker stops being a suspendable worker.
Jump to the script's initial code entry-point, and let that run until it either returns, fails to catch an exception, or gets prematurely aborted by the "kill a worker" or "terminate a worker" algorithms defined below.
If worker global scope is actually a
DedicatedWorkerGlobalScope
object (i.e. the worker is
a dedicated worker), then enable the port message
queue of the worker's implicit port.
Event loop: Wait until either there is a task in one of the event loop's task queues or worker global scope's closing flag is set to true.
Run the oldest task on one of the event loop's task queues, if any. The user agent may pick any task queue.
The handling of events or the execution of callbacks might get prematurely aborted by the "kill a worker" or "terminate a worker" algorithms defined below.
If the storage mutex is now owned by the worker's event loop, release it so that it is once again free.
Remove the task just run in the earlier step, if any, from its task queue.
If there are any more events in the event loop's task queues or if worker global scope's closing flag is set to false, then jump back to the step above labeled event loop.
Empty the worker global scope's list of active timers.
Disentangle all the ports in the list of the worker's ports.
When a user agent is to kill a worker it must run the following steps in parallel with the worker's main loop (the "run a worker" processing model defined above):
Set the worker's WorkerGlobalScope
object's closing flag to
true.
If there are any tasks queued in the event loop's task queues, discard them without processing them.
Wait a user-agent-defined amount of time.
Abort the script currently running in the worker.
User agents may invoke the "kill a worker" processing model on a worker at any time, e.g. in response to user requests, in response to CPU quota management, or when a worker stops being an active needed worker if the worker continues executing even after its closing flag was set to true.
When a user agent is to terminate a worker it must run the following steps in parallel with the worker's main loop (the "run a worker" processing model defined above):
Set the worker's WorkerGlobalScope
object's
closing flag to
true.
If there are any tasks queued in the event loop's task queues, discard them without processing them.
Abort the script currently running in the worker.
If the worker's WorkerGlobalScope
object is
actually a DedicatedWorkerGlobalScope
object (i.e. the
worker is a dedicated worker), then empty the port message
queue of the port that the worker's implicit port is
entangled with.
The task source for the tasks mentioned above is the DOM manipulation task source.
Whenever an uncaught runtime script error occurs in one of the
worker's scripts, if the error did not occur while handling a
previous script error, the user agent must report the
error at the URL of the resource that contained
the script, with the position (line number and column number) where
the error occurred, in the origin of the scripts
running in the worker, using the WorkerGlobalScope
object's onerror
attribute.
For shared workers, if the error is still not handled afterwards, or if the error occurred while handling a previous script error, the error may be reported to the user.
For dedicated workers, if the error is still not handled afterwards, or if
the error occurred while handling a previous script error, the user
agent must queue a task to fire an event that uses the
ErrorEvent
interface, with the name error
, that doesn't bubble and is
cancelable, with its message
, filename
, and lineno
attributes initialized
appropriately, at the Worker
object associated with the
worker. If the event is not canceled, the user agent must act as if
the uncaught runtime script error had occurred in the global scope
that the Worker
object is in, thus repeating the entire
runtime script error reporting process one level up.
If the implicit port connecting the worker to its
Worker
object has been disentangled (i.e. if the parent
worker has been terminated), then the user agent must act as if the
Worker
object had no error
event handler and as if that
worker's onerror
attribute
was null, but must otherwise act as described above.
Thus, error reports propagate up to the chain of
dedicated workers up to the original Document
, even if
some of the workers along this chain have been terminated and
garbage collected.
The task source for the task mentioned above is the DOM manipulation task source.
[Constructor(DOMString type, optional ErrorEventInit eventInitDict)] interface ErrorEvent : Event { readonly attribute DOMString message; readonly attribute DOMString filename; readonly attribute unsigned long lineno; }; dictionary ErrorEventInit : EventInit { DOMString message; DOMString filename; unsigned long lineno; };
The message
attribute
must return the value it was initialized to. When the object is
created, this attribute must be initialized to the empty string. It
represents the error message.
The filename
attribute must return the value it was initialized to. When the
object is created, this attribute must be initialized to the empty
string. It represents the absolute URL of the script in
which the error originally occurred.
The lineno
attribute must return the value it was initialized to. When the
object is created, this attribute must be initialized to zero. It
represents the line number where the error occurred in the
script.
AbstractWorker
abstract interface[NoInterfaceObject] interface AbstractWorker { attribute EventHandler onerror; };
The following are the event handlers (and their
corresponding event handler
event types) that must be supported, as IDL attributes, by
objects implementing the AbstractWorker
interface:
Event handler | Event handler event type |
---|---|
onerror | error
|
Worker
interface[Constructor(DOMString scriptURL)] interface Worker : EventTarget { void terminate(); void postMessage(any message, optional sequence<Transferable> transfer); attribute EventHandler onmessage; }; Worker implements AbstractWorker;
The terminate()
method,
when invoked, must cause the "terminate a worker"
algorithm to be run on the worker with with the object is
associated.
Worker
objects act as if they had an implicit
MessagePort
associated with them. This port is part of
a channel that is set up when the worker is created, but it is not
exposed. This object must never be garbage collected before the
Worker
object.
All messages received by that port must immediately be retargeted
at the Worker
object.
The postMessage()
method on Worker
objects
must act as if, when invoked, it
immediately invoked the method of the same name on the port, with
the same arguments, and returned the same return value.
The postMessage()
method's first argument can be structured data:
worker.postMessage({opcode: 'activate', device: 1938, parameters: [23, 102]});
The following are the event handlers (and their
corresponding event handler
event types) that must be supported, as IDL attributes, by
objects implementing the Worker
interface:
Event handler | Event handler event type |
---|---|
onmessage | message
|
When the Worker(scriptURL)
constructor is invoked, the
user agent must run the following steps:
Resolve the scriptURL argument relative to the entry script's base URL, when the method is invoked.
If this fails, throw a SyntaxError
exception.
If the <scheme> component of
the resulting absolute URL is not "data
", and the origin of
the resulting absolute URL is not the same as the origin of the entry
script, then throw a SecurityError
exception
and abort these steps.
Thus, scripts must either be external files with
the same scheme, host, and port as the original page, or data:
URLs. For
example, you can't load a script from a javascript:
URL, and an
https:
page couldn't start workers using scripts with
http:
URLs.
Create a new DedicatedWorkerGlobalScope
object
whose worker origin is the origin of the entry
script. Let worker global scope be this
new object.
Create a new Worker
object, associated with
worker global scope. Let worker be this new object.
Create a new MessagePort
object
owned by the global
object of the script that
invoked the constructor. Let this be the outside
port.
Associate the outside port with worker.
Create a new MessagePort
object
owned by worker global scope. Let inside port be this new object.
Associate inside port with worker global scope.
Entangle outside port and inside port.
Return worker, and run the following steps asynchronously.
Enable outside port's port message queue.
Let docs be the list of relevant
Document
objects to add given the global object of the script that invoked the
constructor.
Add to
worker global scope's list of the
worker's Document
s the
Document
objects in docs.
If the global object
of the script that invoked the
constructor is a WorkerGlobalScope
object (i.e. we
are creating a nested worker), add worker global
scope to the list of the worker's workers of the
WorkerGlobalScope
object that is the global object of the script that invoked the
constructor.
Run a worker for the resulting absolute URL, with the script's browsing context of the script that invoked the method as the owner browsing context, with the script's document of the script that invoked the method as the owner document, with the origin of the entry script as the owner origin, and with worker global scope as the global scope.
This constructor must be visible when the script's global
object is either a Window
object or an object
implementing the WorkerUtils
interface.
SharedWorker
interface[Constructor(DOMString scriptURL, optional DOMString name)] interface SharedWorker : EventTarget { readonly attribute MessagePort port; }; SharedWorker implements AbstractWorker;
The port
attribute must return the value it was assigned by the object's
constructor. It represents the MessagePort
for
communicating with the shared worker.
When the SharedWorker(scriptURL, name)
constructor is invoked, the user agent must run the following
steps:
Resolve the scriptURL argument.
If this fails, throw a SyntaxError
exception.
Otherwise, let scriptURL be the resulting absolute URL.
Let name be the value of the second argument, or the empty string if the second argument was omitted.
If the <scheme> component of
scriptURL is not "data
", and the origin of
scriptURL is not the same as the origin of the entry
script, then throw a SecurityError
exception
and abort these steps.
Thus, scripts must either be external files with
the same scheme, host, and port as the original page, or data:
URLs. For
example, you can't load a script from a javascript:
URL, and an
https:
page couldn't start workers using scripts with
http:
URLs.
Let docs be the list of relevant
Document
objects to add given the global object of the script that invoked the
constructor.
Execute the following substeps atomically:
Create a new SharedWorker
object, which will
shortly be associated with a SharedWorkerGlobalScope
object. Let this SharedWorker
object be worker.
Create a new MessagePort
object
owned by the global
object of the script that invoked the method. Let this be
the outside port.
Assign outside port to the port
attribute of worker.
Let worker global scope be null.
If name is not the empty string and there
exists a SharedWorkerGlobalScope
object whose closing flag is
false, whose name
attribute is
exactly equal to name, and whose
worker origin is the same origin as
scriptURL, then let worker
global scope be that SharedWorkerGlobalScope
object.
Otherwise, if name is the empty string
and there exists a SharedWorkerGlobalScope
object
whose closing
flag is false, whose name
attribute is the
empty string, and whose location
attribute
represents an absolute URL that is exactly equal to
scriptURL, then let worker
global scope be that SharedWorkerGlobalScope
object.
If worker global scope is not null, but the user agent has been configured to disallow communication between the script that invoked the constructor and the worker represented by the worker global scope, then set worker global scope to null.
For example, a user agent could have a development mode that isolates a particular top-level browsing context from all other pages, and scripts in that development mode could be blocked from connecting to shared workers running in the normal browser mode.
If worker global scope is not null, then run these steps:
If worker global scope's location
attribute represents an absolute URL that is not
exactly equal to scriptURL, then throw a
URLMismatchError
exception and abort all these
steps.
Associate worker with worker global scope.
Create a new MessagePort
object owned by worker global
scope. Let this be the inside
port.
Entangle outside port and inside port.
Return worker and perform the next step asynchronously.
Create an event that uses the MessageEvent
interface, with the name connect
, which does not bubble, is
not cancelable, has no default action, has a data
attribute whose value
is initialized to the empty string, has a ports
attribute whose
value is initialized to a read only array containing
only the newly created port, and has a source
attribute whose
value is initialized to the newly created port, and queue
a task to dispatch the event at worker
global scope.
Add to
worker global scope's list of the
worker's Document
s the
Document
objects in docs.
If the global
object of the script
that invoked the constructor is a
WorkerGlobalScope
object, add worker global scope to the list of the
worker's workers of the WorkerGlobalScope
object that is the global
object of the script
that invoked the constructor.
Abort all these steps.
Create a new SharedWorkerGlobalScope
object
whose worker origin is the origin of the entry
script. Let worker global scope be
this new object.
Associate worker with worker global scope.
Set the name
attribute of
worker global scope to name.
Create a new MessagePort
object
owned by worker global scope. Let inside port be this new object.
Entangle outside port and inside port.
Return worker and perform the remaining steps asynchronously.
Create an event that uses the MessageEvent
interface, with the name connect
, which does not bubble, is not
cancelable, has no default action, has a data
attribute whose value is
initialized to the empty string, has a ports
attribute whose value
is initialized to a read
only array containing only the newly created port, and has a
source
attribute whose
value is initialized to the newly created port, and queue a
task to dispatch the event at worker global
scope.
Add to
worker global scope's list of the
worker's Document
s the
Document
objects in docs.
If the global object
of the script that invoked the
constructor is a WorkerGlobalScope
object, add worker global scope to the list of the
worker's workers of the WorkerGlobalScope
object that is the global
object of the script
that invoked the constructor.
Run a worker for scriptURL, with the script's browsing context of the script that invoked the method as the owner browsing context, with the script's document of the script that invoked the method as the owner document, with the origin of the entry script as the owner origin, and with worker global scope as the global scope.
This constructor must be visible when the script's global
object is either a Window
object or an object
implementing the WorkerUtils
interface.
The task source for the tasks mentioned above is the DOM manipulation task source.
[NoInterfaceObject] interface WorkerUtils { void importScripts(DOMString... urls); readonly attribute WorkerNavigator navigator; }; WorkerUtils implements WindowTimers; WorkerUtils implements WindowBase64;
The DOM APIs (Node
objects, Document
objects, etc) are not available to workers in this version of this
specification.
When a script invokes the importScripts(urls)
method on a
WorkerGlobalScope
object, the user agent must run the
following steps:
If there are no arguments, return without doing anything. Abort these steps.
Resolve each argument.
If any fail, throw a SyntaxError
exception.
Attempt to fetch each resource identified by the resulting absolute URLs, from the entry script's origin, with the synchronous flag set.
For each argument in turn, in the order given, starting with the first one, run these substeps:
Wait for the fetching attempt for the corresponding resource to complete.
If the fetching attempt failed, throw a
NetworkError
exception and abort all these
steps.
If the attempt succeeds, then let source be the script resource decoded as UTF-8, with error handling.
Let language be JavaScript.
As with the worker's script, the script here is always assumed to be JavaScript, regardless of the MIME type.
Create a script, using source as the script source, the URL from which source was obtained, and language as the scripting language, using the same global object, browsing context, URL character encoding, base URL, and script group as the script that was created by the worker's run a worker algorithm.
Let the newly created script run until it either returns, fails to parse, fails to catch an exception, or gets prematurely aborted by the "kill a worker" or "terminate a worker" algorithms defined above.
If it failed to parse, then throw an ECMAScript
SyntaxError
exception and abort all these
steps. [ECMA262]
If an exception was thrown or if the script was prematurely
aborted, then abort all these steps, letting the exception or
aborting continue to be processed by the script that called the
importScripts()
method.
If the "kill a worker" or "terminate a worker" algorithms abort the script then abort all these steps.
WorkerNavigator
objectThe navigator
attribute
of the WorkerUtils
interface must return an instance of
the WorkerNavigator
interface, which represents the
identity and state of the user agent (the client):
interface WorkerNavigator {}; WorkerNavigator implements NavigatorID; WorkerNavigator implements NavigatorOnLine;
Objects implementing the WorkerNavigator
interface
also implement the NavigatorID
and
NavigatorOnLine
interfaces.
The WorkerNavigator
interface must only be exposed if the JavaScript global
environment is a worker environment.
Nothing must be exposed when the JavaScript global environment is a worker environment except for the following:
XMLHttpRequest
and all interface objects and
constructors defined by the XMLHttpRequest specifications, except
that the document response entity body must always be
null. The XMLHttpRequest
base URL is the
script's base URL; the
XMLHttpRequest
origin is the script's
origin. [XHR]
The interface objects and constructors defined by this specification, except where is further restricted by explicit requirements in this specification.
The interface objects of any objects made accessible through interfaces implemented by any objects that are themselves exposed (i.e. this requirement is transitive).
These requirements do not override the requirements
defined by the Web IDL specification, in particular concerning the
visibility of interfaces annotated with the [NoInterfaceObject]
extended attribute.
interface WorkerLocation { // URL decomposition IDL attributes stringifier readonly attribute DOMString href; readonly attribute DOMString protocol; readonly attribute DOMString host; readonly attribute DOMString hostname; readonly attribute DOMString port; readonly attribute DOMString pathname; readonly attribute DOMString search; readonly attribute DOMString hash; };
A WorkerLocation
object represents an absolute
URL set at its creation.
The href
attribute must return the absolute URL that the object
represents.
The WorkerLocation
interface also has the complement
of URL decomposition IDL attributes, protocol
,
host
, port
, hostname
,
pathname
,
search
,
and hash
.
These must follow the rules given for URL decomposition IDL
attributes, with the input being the absolute
URL that the object represents (same as the href
attribute), and the
common setter action being a
no-op, since the attributes are defined to be readonly.
The WorkerLocation
interface must only be exposed if the JavaScript global
environment is a worker environment.