Abstract

This document describes APIs for clipboard operations such as copy, cut and paste in web applications.

Status of This Document

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 a Working Draft. This document is intended to become a W3C Recommendation. If you wish to make comments regarding this document, please send them to public-webapps@w3.org (subscribe, archives), with a Subject: prefix of [clipboard-apis]. All comments are welcome.

Publication as a Working 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.

Table of Contents

1. Conformance

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].

2. Introduction

This section is non-normative.

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.

3. Use Cases

This section is non-normative.

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.

3.1 Rich content editing

When copying text which contains hyperlinks or other structure, it is often useful to be able to reformat the content to preserve important information.

3.2 Graphics with built-in semantics

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.

3.3 Mathematical information

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.

4. APIs from other specifications

The following items are defined in the HTML specification. [HTML5]

The following items are defined in the DOM specification [DOM]

5. Events

5.1 Event types and details

This section contains a high-level description of how clipboard events work. Further implementation details are given in the processing model section.

5.1.1 copy event

When the user initiates a copy operation, the implementation fires a clipboard event named copy. Its default action is to place the selected data on the clipboard.

The current selection is not affected. The event bubbles and is cancelable.

If content in the document is selected, the default action of a copy event is to place the selection on the clipboard. Any script which uses the clipboardData API to control what the cut event will write to the clipboard 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.

If there is no selection, the clipboard is not modified except if the default action is prevented and the script has added entries in the DataTransferItemList, for example by calling the setData() method.

5.1.2 cut event

When the user initiates a cut operation, the implementation fires a clipboard event named cut. In an editable context, its default action is to place the selected data on the clipboard and remove the selection from the document.

The event bubbles and is cancelable.

In a non-editable context, or if there is no selection, the cut event's default action is to do nothing. The implementation fires the event regardless. If the default action is to do nothing, the clipboard is not modified except if the default action is prevented and the script has added entries in the DataTransferItemList.

The cut event fires before the selected data is removed. When the cut operation is completed, the selection is collapsed.

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. Any script which uses the clipboardData API to control what the cut event will write to the clipboard 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.

5.1.3 paste event

When the user initiates a paste operation, the implementation fires a clipboard event named paste. The event fires before any clipboard data is inserted.

The event bubbles and is cancelable.

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 the event fires regardless.

When pasting, the drag data store mode flag is read-only, hence calling setData() from a paste event handler will not modify the data that is inserted, and not modify the data on the clipboard.

5.1.4 beforecopy event

If the implementation has user interface controls that users can use to initiate a copy operation, the user agent should determine what state such controls should be in by firing a beforecopy event before the control is shown to the user (i.e. in a menu). The default action of the beforecopy event is to disable any 'copy'-related UI controls if there is no selection. The event bubbles and is cancelable.

5.1.5 beforecut event

If the implementation has user interface controls that users can use to initiate a cut operation, the user agent should determine what state such controls should be in by firing a beforecut event before the control is shown to the user (i.e. in a menu). The default action of the beforecut event is to disable any 'cut'-related UI controls if there is no selection in an editable context. The event bubbles and is cancelable.

5.1.6 beforepaste event

If the implementation has user interface controls that users can use to initiate a paste operation, the user agent should determine what state such controls should be in by firing a beforepaste event before the control is shown to the user (i.e. in a menu). The default action of the before event is to disable any 'paste'-related UI controls if there is no editable context. The event bubbles and is cancelable.

Note

These events can not be used to disable UI controls that would otherwise be enabled. The use case for beforecopy, beforecut and beforepaste events is to enable UI elements that would otherwise be disabled, by allowing the script to indicate that it will handle clipboard operations even though there is no selection or editable context.

6. Processing model

To dispatch a clipboard event of type e,

  1. Let the data transfer be a DataTransfer object [HTML5]
  2. Let clear-was-called be false
  3. Let trusted be true if the event is generated by the user agent, false otherwise
  4. If the event is not trusted, let semi-trusted be true or false according to the semi-trusted events rules
  5. Let types-to-clear be an empty list
  6. Let clipboard-entry be the sequence number of the current clipboard content, or null if the OS clipboard does not support sequence numbers
  7. If the context is editable, let event target be the element that contains the start of the selection in document order, or the BODY element if there is no selection or cursor. If the context is not editable, let event target be the focused node, or the BODY element if no node has focus.
  8. If e is paste

    Set the associated DataTransfer object's drag data store mode flag to read-only

    If trusted is true
    If the implementation is configured to allow scripted paste actions and the data and dataType properties were not set on the ClipboardEventInit object passed to the event constructor:

    For each part on the OS clipboard, carry out these steps:

    If the current clipboard part contains plain text:
    1. Ensure the text is in the encoding the scripting engine uses internally
    2. Add one entry for the text to the DataTransferItemList with drag data item kind set to string and drag data item type string set to text/plain
    If the current clipboard part represents file references:
    1. Determine MIME type of referenced files
    2. Add one entry per file reference to the DataTransferItemList with drag data item kind set to file and drag data item type string set to the corresponding MIME type, or application/octet-stream if the file's type is unknown.
    If the current clipboard part contains HTML- or XHTML-formatted text, according to the operating system's convention for describing such clipboard formats

    If the implementation supports pasting HTML, the implementation must process the markup according to the following steps:

    1. Add one entry to the 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.
    2. Extract the markup from the clipboard and use the relevant parser to construct a DOM tree
    3. If the markup's source URL is known, resolve all relative URLs in HREF and SRC attributes using the source URL as base URL, and set the respective attributes to the resolved absolute URL
    4. If the markup's origin is from a local application, check whether there are references to local files and/or other parts of the OS clipboard's contents. If such references are found, references to sub-parts must be replaced by content-id references using the cid: URL scheme [RFC2392]. To do so, process each attribute referencing a local file or clipboard part according to the following steps:
      1. Let itemNumber be the number of items on the DataTransferItemList
      2. Choose the appropriate steps from this list:

        If the DataTransferItemList of the current DataTransfer object already contains an entry for the referenced file or clipboard part
        set itemNumber to the index of the existing entry
        Otherwise
        1. Add a new entry to the DataTransferItemList 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, or application/octet-stream if the file's type is unknown.
        2. Let the new entry's internal file name be the file name part of the HTML attribute contents
        3. Let the new entry's last modified date be the timestamp of the referenced file or 0 if the entry references a clipboard part
      3. Update the DOM attribute that referenced the local file or clipboard part to contain the string 'cid:' followed by itemNumber.
    5. Serialize the processed DOM and update the DataTransferItemList entry referenced by mainPartIndex with the resulting HTML code
    If the current clipboard part contains data in another supported binary or text-based format:
    1. Determine the MIME type of the data
    2. Add one entry to the DataTransferItemList with drag data item kind set to file, drag data item type string set to the corresponding MIME type
    Otherwise, the event is untrusted. Follow the steps in this algorithm:
    If the arguments data and dataType were passed to the ClipboardEvent constructor
    Add one entry for the data to the DataTransferItemList with drag data item kind set to string and drag data item type string set to the value of the dataType argument
    Otherwise,
    Leave the DataTransferItemList empty

    Update the files property to match entries in the DataTransferItemList.

    Update the types property to match entries in the DataTransferItemList.

    If e is copy or cut

    Set the associated DataTransfer object's drag data store mode flag to read/write

  9. Dispatch an event using the ClipboardEvent interface, with its type attribute initialized to e, its isTrusted attribute initialized to trusted, its bubbles attribute set to true, its cancelable attribute set to true, and its clipboardData attribute initialized to data transfer, at event target.

    Implementation requirements for access to data during event dispatch are defined in [HTML5]. Some additional clipboard event-specific processing rules are given below:

    If a script calls clearData() or items.clear() and the DataTransfer object's drag data store mode flag is read/write
    set the clear-was-called flag to true. If an argument is given, add the argument to the types-to-clear list.
    If a script calls setData() or modifies items and the clear-was-called flag is true
    If the types-to-clear list is empty
    set the clear-was-called flag to false
    else, if setData()'s type argument or the new item's drag data item type string is found in the types-to-clear list
    remove it from the list. If the list is now empty, set the clear-was-called flag to false
    If a script calls getData() or accesses items in the DataTransferItemList and clipboard-entry is set
    check that the clipboard data's sequence number matches clipboard-entry. If the clipboard no longer contains the same entry, set the DataTransferItemList object's drag data store mode to the disabled mode

    Warning! 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.

  10. When event processing is complete, follow these steps:
    If e is paste
    If the event was cancelled
    Do nothing, terminate this algorithm.
    Otherwise

    If the cursor or selection is in an editable context, insert any data suitable for that context from the event's DataTransferItemList. Queue tasks to fire any events that should fire due to the modification, see interaction with other events for details.

    Note

    The DataTransferItemList of an untrusted paste event will only contain data if data and dataType arguments were passed to the ClipboardEvent constructor.

    Else, if e is copy or cut
    If the event was cancelled

    Update the clipboard contents with the data from the script, as given by the DataTransferItemList. Process each part as follows:

    If the list of items is empty and the clear-was-called flag is true
    If the types-to-clear list is empty
    Clear the clipboard
    else
    Remove types in the types-to-clear list from the clipboard in an operating system and implementation-specific way
    If data type is text/plain
    1. Ensure encoding is correct per OS and locale conventions
    2. Normalize line endings according to platform conventions
    3. Remove current clipboard contents
    4. Place text on clipboard
    Otherwise
    1. Remove current clipboard contents
    2. Place part on clipboard with the appropriate OS clipboard format description
    Note

    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.

    Otherwise
    If there is a selection
    Remove current clipboard contents
    If the event was a copy event
    Place contents of selection on the clipboard
    If the event was a cut event and the context is editable
    Place contents of selection on the clipboard
    Remove selection contents and collapse the selection
    Otherwise

    Do nothing, terminate this algorithm

    Note

    Calling setData() without calling preventDefault() has no effect, even if there is no selection - the default action is to do nothing.

7. Clipboard event interfaces

The ClipboardEvent interface extends the Event interface.

The interface can be used to construct events. An example is given below:

Example 1
var pasteEvent = new ClipboardEvent('paste', { dataType: 'text/plain', data: 'My string' } );
document.dispatchEvent(pasteEvent);
dictionary ClipboardEventInit : EventInit {
    DOMString data = "";
    DOMString dataType = "";
};

7.1 Dictionary ClipboardEventInit Members

data of type DOMString, defaulting to ""
The data of the synthetic clipboard event
dataType of type DOMString, defaulting to ""
A MIME type [RFC2046] describing the data the event is being initialized with
[Constructor(DOMString type, optional ClipboardEventInit eventInitDict)]
interface ClipboardEvent : Event {
    readonly    attribute DataTransfer clipboardData;
};

7.2 Attributes

clipboardData of type DataTransfer, readonly

The clipboardData attribute is an instance of the DataTransfer interface which lets a script read and manipulate values on the system clipboard during user-initiated copy, cut and paste operations. The associated drag data store is a live but filtered view of the system clipboard, exposing data types the implementation knows the script can safely access.

The clipboardData object's items and files properties enable processing of multi-part or non-textual data from the clipboard.

8. Integration with other scripts and events

8.1 Semi-trusted events

A copy or cut event dispatched from an event thread with the isTrusted attribute set to true and whose event type is found in the list below, is a semi-trusted event. Event listeners for such events may modify the data on the clipboard.

Events that are allowed to trigger semi-trusted events are:

The implementation may allow other trusted event types to trigger semi-trusted events if the implementation authors believe that those event types are likely to express user intention.

Synthetic paste events must not give a script access to data on the real system clipboard, unless the user agent is configured to allow scripted paste actions.

Synthetic cut and copy events whose semi-trusted property is false must not modify data on the system clipboard.

The default action of a synthetic paste event is to insert any data passed to the event constructor, if that data is suitable for the event target. If the data type is not suitable for the event target, data must not be inserted.

8.2 Integration with rich text editing APIs

If an implementation supports the document.execCommand method and allows calling it with the commands "cut", "copy" and "paste", the implementation must dispatch corresponding synthetic clipboard events. Such events are not trusted, but may be semi-trusted events.

Note

Synthetic events and events triggered from document.execCommand() will only affect the contents of the real clipboard if the user agent is configured to trust the script, or (for copy and cut events only) if the synthetic event is dispatched from an event that is trusted and whitelisted.

8.3 Interaction with other events

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.

8.4 Event listeners that modify selection or focus

If the event listener modifies the selection or focus, the clipboard action must be completed on the modified selection.

9. Pasting HTML and multi-part data

9.1 Security risks

This section is non-normative.

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 possible security policies:

Origin of dataOrigin of scriptRules
Originates from online sourceSame as dataDo not sanitize HTML. Do not access any local files.
Different originOptionally sanitize content. Do not access any local files.
Originates from local applicationAnyDo not sanitize HTML. Grant access to local files

Some implementations mitigate the risks associated with pasting rich text by stripping potentially malicious content such as SCRIPT elements and javascript: links by default when pasting rich text, but allow a paste event handler to retrieve and process the original, un-sanitized data.

9.2 General security policies

The implementation must not download referenced online resources, or expose their contents in the files list 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.

10. Other security and privacy considerations

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.

10.1 Privacy concerns

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 user agent'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.

10.2 Nuisance considerations

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.

11. Mandatory data types

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.

12. Acknowledgements

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, Glenn Maynard, James Graham, James Greene, Boris Zbarsky.

A. References

A.1 Normative references

[DOM]
Anne van Kesteren; Aryeh Gregor; Ms2ger. DOM Standard. Living Standard. URL: http://dom.spec.whatwg.org
[HTML5]
Robin Berjon; Steve Faulkner; Travis Leithead; Erika Doyle Navara; Edward O'Connor; Silvia Pfeiffer. HTML5. 4 February 2014. W3C Candidate Recommendation. URL: http://www.w3.org/TR/html5/
[RFC2046]
N. Freed; N. Borenstein. Multipurpose Internet Mail Extensions (MIME) Part Two: Media Types (RFC 2046). November 1996. RFC. URL: http://www.ietf.org/rfc/rfc2046.txt
[RFC2119]
S. Bradner. Key words for use in RFCs to Indicate Requirement Levels. March 1997. Internet RFC 2119. URL: http://www.ietf.org/rfc/rfc2119.txt
[RFC2392]
E. Levinson. Content-ID and Message-ID Uniform Resource Locators. August 1998. Internet RFC 2392.. URL: http://www.ietf.org/rfc/rfc2392.txt

A.2 Informative references

[MICROSOFT-CLIP-OP]
About DHTML Data Transfer. Microsoft Developer Network.. URL: http://msdn.microsoft.com/en-us/library/ms537658.aspx