Copyright © 2010-2012 W3C® (MIT, ERCIM, Keio), All Rights Reserved. W3C liability, trademark and document use rules apply.
This document describes APIs for clipboard operations such as copy, cut and paste in web applications.
This section describes the status of this document at the time of its publication. Other documents may supersede this document. A list of current W3C publications and the latest revision of this technical report can be found in the W3C technical reports index at http://www.w3.org/TR/.
This document was published by the Web Applications Working Group as an Editor's Draft. If you wish to make comments regarding this document, please send them to public-webapps@w3.org (subscribe, archives). All feedback is welcome.
Publication as an Editor's Draft does not imply endorsement by the W3C Membership. This is a draft document and may be updated, replaced or obsoleted by other documents at any time. It is inappropriate to cite this document as other than work in progress.
This document was produced by a group operating under the 5 February 2004 W3C Patent Policy. W3C maintains a public list of any patent disclosures made in connection with the deliverables of the group; that page also includes instructions for disclosing a patent. An individual who has actual knowledge of a patent which the individual believes contains Essential Claim(s) must disclose the information in accordance with section 6 of the W3C Patent Policy.
As well as sections marked as non-normative, all authoring guidelines, diagrams, examples, and notes in this specification are non-normative. Everything else in this specification is normative.
The key words must, must not, required, should, should not, recommended, may, and optional in this specification are to be interpreted as described in [RFC2119].
This section is informative
This specification defines the common clipboard operations of cutting, copying and pasting, in such a way that they are exposed to Web Applications and can be adapted to provide advanced functionalities. Its goal is to provide for compatibility where possible with existing implementations.
This section is informative
There are many use cases for being able to change the default clipboard operations (cut/copy/paste). We have collected a few samples to demonstrate possible uses, although these may not all be supported by this specification.
When copying text which contains hyperlinks or other structure, it is often useful to be able to reformat the content to preserve important information.
In order to make web applications which allow the manipulation of rich text, or of graphic content such as SVG, it is useful to provide a mechanism that allows for copying more than just the rendered content.
With content such as mathematics, simply copying rendered text and pasting it into another application generally leads to most of the semantics being lost. MathML often needs to be transformed to be copied as plain text, for example to make sure "to the power of" is shown with the caret "^" sign in a formula plain-text input. The XML source could also be placed in the clipboard with the appropriate transformation occurring at paste time.
When the user initiates a copy operation, the implementation must fire a copy event. Its default action is to place the selected data on the clipboard.
The current selection must not be affected.
If there is no selection, the clipboard must not be modified except if the default action is prevented and the script has added entries in the DataTransferItemList.
When the user initiates a cut operation, the implementation must fire a cut event. In an editable context, its default action is to place the selected data on the clipboard and remove the selection from the document.
In a non-editable context, or if there is no selection, the cut event's default action is to do nothing. The implementation must fire the event regardless. If the default action is to do nothing, the clipboard must not be modified except if the default action is prevented and the script has added entries in the DataTransferItemList.
The cut event must fire before the selected data is removed. When the cut operation is completed, the selection must be collapsed.
When the user initiates a paste operation, the implementation must fire a paste event. The event must fire before any clipboard data is inserted.
If the cursor is in an editable element, the default action is to insert clipboard data in the most suitable format supported for the given context.
The paste event has no default action in a non-editable context, but implementations must fire the event regardless.
These are the general steps to follow when firing clipboard events.
DataTransfer object [HTML5-DND] which the event.clipboardData property will refer toDetermine the target node for the event as follows
In an editable context, the event object's target property must refer to the element that contains the start of the selection in document order, i.e. the end that is closer to the beginning of the document. If there is no selection or cursor, the target is the BODY element [HTML5].
In a non-editable document, the event's target must refer to a node focused for example by clicking, using the tab key, or by an interactive cursor, or to the BODY element [HTML5] if no other node has focus.
Prepare for firing the event per the event type specific instructions below:
Set the associated DataTransfer object's drag data store mode flag to read-only
For each part on the OS clipboard, carry out these steps:
DataTransferItemList with drag data item kind set to file and drag data item type string set to the corresponding MIME type
What if the MIME type is unknown? Use application/octet-stream?
If the implementation supports pasting HTML, the implementation must process the markup according to the following steps:
DataTransferItemList with drag data item kind set to Plain Unicode string, drag data item type string set to text/html or application/xhtml+xml accordingly. Let mainPartIndex be the index of this entry in the DataTransferItemList.DataTransferItemListChoose the appropriate steps from this list:
DataTransferItemList of the current DataTransfer object already contains an entry for the referenced file or clipboard partDataTransferItemList with index set to itemNumber, drag data item kind set to "file", and drag data item type string set to the MIME type of the file or clipboard part if known. DataTransferItemList entry referenced by mainPartIndex with the resulting HTML codeDataTransferItemList with drag data item kind set to file, drag data item type string set to the corresponding MIME typeUpdate the files property to match entries in the DataTransferItemList.
Update the types property to match entries in the DataTransferItemList.
Set the associated DataTransfer object's drag data store mode flag to read/write
Fire the event [DOM-LEVEL-2-EVENTS]. Implementation requirements for access to data during event dispatch is defined in [HTML5-DND]. Some additional clipboard event-specific processing rules are given below:
DataTransfer object's drag data store mode flag is read/writetype argument or the new item's drag data item type string is found in the types-to-clear listDataTransferItemList and clipboard-entry is setDataTransferItemList object's drag data store mode to the disabled modeWarning: A malicious script listening to a paste event may set up a never-ending loop in order to read what the user places on the clipboard in the future. On platforms where a clipboard sequence number is not available, other limitations should be implemented.
Process the default action or the data from the script per the following instructions:
Update the clipboard contents with the data from the script, as given by the DataTransferItemList. Process each part as follows:
Do nothing, terminate this algorithm
Calling setData() without calling preventDefault() has no effect, even if there is no selection - the default action is to do nothing.
The ClipboardEvent interface extends the Event interface [DOM-LEVEL-2-EVENTS].
A synthetic paste event must not give a script access to data on the real system clipboard. Synthetic cut and copy events must not modify data on the system clipboard.
The default action of a synthetic paste event with text/plain data when dispatched in an editable context, is to insert the data.
dictionary ClipboardEventInit : EventInit {
attribute DOMString data;
attribute DOMString dataType;
};
ClipboardEventInit Membersdata of type attribute DOMStringdataType of type attribute DOMString[Constructor(DOMString type, optional ClipboardEventInit eventInitDict)]
interface ClipboardEvent : Event {
readonly attribute DataTransfer clipboardData;
};
clipboardData of type DataTransfer, readonlyThe interface can be used to construct event objects per [DOM-CORE-DRAFT]. An example is given below:
var pasteEvent = new ClipboardEvent('paste', { bubbles: true, cancelable: true, dataType: 'text/plain', data: 'My string' } );
document.dispatchEvent(pasteEvent);
This section is informative, and describes only the parts of the DataTransfer interface that are relevant for clipboard events. The normative specification for the DataTransfer interface is found in [HTML5-DND]'s DataTransfer interface section.
interface clipboardData : DataTransfer {
attribute DataTransferItemList items;
attribute DOMStringList types;
readonly attribute FileList files;
DOMString getData (DOMString type);
boolean setData (DOMString type, DOMString data);
boolean clearData (optional DOMString type);
};
files of type FileList, readonlyitems of type DataTransferItemListtypes of type DOMStringListclearDataCalling clearData() empties the system clipboard, or removes the specified type of data from the clipboard. See HTML5 for details [HTML5-DND].
| Parameter | Type | Nullable | Optional | Description |
|---|---|---|---|---|
| type | DOMString | ? | ? | The type of data to clear |
booleangetDataCalling getData() from within a paste event handler will return the clipboard data in the specified format. See HTML5 for details [HTML5-DND].
Implementations are encouraged to support 'text/html' to retrieve any HTML formatted data on the system clipboard, but see the security section of this spec for security and privacy concerns.
| Parameter | Type | Nullable | Optional | Description |
|---|---|---|---|---|
| type | DOMString | ? | ? | The type of data to get |
DOMStringsetDataCalling setData() from within an copy/cut event handler modifies the data which will be placed on the clipboard, for the specified format. See HTML5 for details [HTML5-DND]
Note: Due to limitations in the implementation of operating system clipboards, scripts should not assume that custom formats will be available to other applications on the system. For example, there is a limit to how many custom clipboard formats can be registered in Microsoft Windows. While it is possible to use any string for setData()'s type argument, sticking to well-known types is strongly recommended.
There should be a way a script can check if a clipboard format is registered and whether the implementation allows writing this format to the clipboard!
Calling setData() from a paste event handler must not modify the data that is inserted, and must not modify the data on the clipboard.
If content in the document is selected, the default action of a copy event is to place the selection on the clipboard. If content is selected and the selection is in an editable context, the default action of a cut event is to place the selection on the clipboard and remove it from the document. Hence, the script calling setData() also needs to cancel the default action of the event with event.preventDefault(). Otherwise, the data the script intends to place on the clipboard will be overwritten by the default action.
| Parameter | Type | Nullable | Optional | Description |
|---|---|---|---|---|
| type | DOMString | ? | ? | The type of data being placed on the clipboard |
| data | DOMString | ? | ? | The data being added to the clipboard |
booleanIf an implementation supports the document.execCommand method and allows calling it with the commands "cut", "copy" and "paste", the implementation must fire the corresponding events. The event is syncronous and may prevent the execCommand() call from having its normal effect.
If the clipboard operation is triggered by keyboard input, the implementation must fire the corresponding event as the default action of the keydown event that initiates the clipboard operation. For example, if the user presses Ctrl-C to copy, dispatching a copy event must be the default action of the C key's keydown event. The event is asynchronous but must be dispatched before keyup events for the relevant keys.
The default action of the cut and paste events may cause the implementation to dispatch other supported events, such as textInput, input, change, validation events, DOMCharacterDataModified and DOMNodeRemoved / DOMNodeInserted. Any such events are queued up to fire after processing of the cut/paste event is finished.
The implementation must not dispatch other input-related events like textInput, input, change, and validation events in response to the copy operation.
If the event listener modifies the selection or focus, the clipboard action must be completed on the modified selection.
This section is informative.
There are certain security risks associated with pasting formatted or multi-part data.
To determine what policies to use, the factors we consider are
This is an overview of the scenarios and the intended security policies:
| Origin of data | Origin of script | Rules |
|---|---|---|
| Originates from online source | Same as data | Do not sanitize HTML. Do not access any local files. |
| Different origin | Sanitize content. Do not access any local files. | |
| Originates from local application | Any | Do not sanitize HTML. Grant access to local files |
The implementation must not download referenced online resources, or expose their contents in the FileList or DataTransferItemList.
If the data on the clipboard is not from a local application, the implementation must not give access to any referenced local files.
For example, if the data contains <img src="file://localhost/example.jpg"> but the data's origin is an online resource, the implementation must not add an entry for example.jpg to the clipboardData.items list.
If the data originates from a web site, and the origin of the web site and the origin of the document associated with the script that created the event listener differs, the implementation may apply a sanitization algorithm before exposing HTML data.
This section is informative
Pasting HTML and other markup-based content copied from one site into another site might compromise the security of the former site, for example by giving the second site access to passwords, nonces and other sensitive data that might be embedded in the markup. Implementations may therefore decide to use a cross-origin paste sanitization algorithm to attempt removing hidden data the user is likely not aware of pasting. One example of such an algorithm might be the following:
In order to protect the target site from script injection, the implementation may process the markup to remove scripting languages. One example of such an algorithm might be the following:
Implementations may let the user indicate that an app is trusted to not attack other apps and apply its own safety measures, thus bypass the above algorithm. Implementations may also implement additional restrictions, for example only support text/plain if the user does a cross-origin paste, or only support text/plain if content from an encrypted origin is pasted into a non-encrypted page.
Enabling authors to change what is copied by a user, or to make an automated copy of something that was never selected and allowing unrestricted calls to paste information can raise various security and privacy concerns.
An example scenario of a problem is where a user selects a link and copies it, but a different link is copied to the clipboard. The effect of this can range from an unexpected result on pasting to an attempted "phishing" attack.
Untrusted scripts should not get uncontrolled access to a user's clipboard data. This specification assumes that granting access to the current clipboard data when a user explicitly initiates a paste operation from the UA's trusted chrome is acceptable. However, implementors must proceed carefully, and as a minimum implement the precautions below:
Implementations may choose to further limit the functionality provided by the DataTransfer interface. For example, an implementation may allow the user to disable this API, or configure which web sites should be granted access to it.
Scripts may use the DataTransfer API to annoy and confuse users by altering the data on the system clipboard from copy and cut events. This specification does not attempt to prevent such nuisances, though implementations may add additional restrictions.
Implementations must handle scripts that try to place excessive amounts of data on the clipboard gracefully.
The implementation must recognise the native OS clipboard format description for the following data types, to be able to populate the DataTransferItemList with the correct description for paste events, and set the correct data format on the OS clipboard in response to copy and cut events.
What about audio and video types? BMP? RTF? RTF was requested due to embedded images possibility (but this spec allows access to local images referenced in HTML fragments by design..).
Some standard Windows formats we don't handle DataFormats.CF_RTFTEXT DataFormats.CF_WAVE DataFormats.CF_RIFF DataFormats.CF_BITMAP DataFormats.CF_DIB DataFormats.CF_DIF DataFormats.CF_METAFILEPICT DataFormats.CF_PALETTE DataFormats.CF_TIFF
This section is informative
The editors would like to acknowledge their intellectual debt to the documentation of Data Transfer functionalities from Microsoft [MICROSOFT-CLIP-OP] and earlier drafts of the [HTML5] specification. We are also grateful for the draft "safe copy and paste" from Paul Libbrecht (this draft is no longer available on the Web).
We would like to acknowledge the contributions made by the following:
Shawn Carnell, Daniel Dardailler, Al Gilman, Lachlan Hunt, Aaron Leventhal, Jim Ley, Paul Libbrecht, "Martijn", Dave Poehlman, "ROBO Design", Janina Sajka, Rich Schwerdtfeger, Jonas Sicking, Maciej Stachowiak, Mihai Sucan, Tom Wlodkowski, Anne van Kesteren, Tarquin Wilton-Jones, Dmitry Titov, Robert O'Callahan, Ryosuke Niwa, Ian Hickson, Ojan Vafai, Daniel Cheng, Adam Barth, ms2ger.