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 Platform 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). 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.

This document is governed by the 1 September 2015 W3C Process Document.

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 word SHOULD is 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

Algorithms in this document rely on several APIs defined in other web platform specifications and recommendations. Below is a list of all methods, properties and definitions this document relies on.

The following items are defined in the HTML Living Standard specification. [HTMLLS]

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

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

The following items are defined in the HTML Editing APIs specification [HTMLEA]

5. Terminology

The term editable context means any element that is either an editing host, a textarea element, or an input element with its type attribute set to any of text, search, tel, url, email, password or number.

6. Clipboard actions and events

This section defines clipboard actions and events and the processing model for event dispatch.

6.1 Actions

Each action has two flags called script-triggered and script-may-access-clipboard.

The script-triggered flag is set if the action runs because of a script, for example a document.execCommand() call. Future scripting APIs that interact with the clipboard should also use these actions, and the script-triggered flag must be set accordingly.

The script-may-access-clipboard flag is set as follows:

If action is copy or cut and the script thread is allowed to modify the clipboard
Set the action's script-may-access-clipboard flag
If action is paste and the script thread is allowed to read from clipboard
set the action's script-may-access-clipboard flag.

6.1.1 The copy action

Note

When the user initiates a copy action, the implementation fires a clipboard event named copy. If the event is not canceled, the selected data will be copied to the clipboard.

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

A script which uses the event.clipboardData API to control what ends up on the clipboard, needs to cancel the event. Otherwise, the data the script intends to place on the clipboard will be ignored.

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

Example 1
document.addEventListener('copy', function(e){
    e.clipboardData.setData('text/plain', 'Hello, world!');
    e.clipboardData.setData('text/html', '<b>Hello, world!</b>');
    e.preventDefault(); // We want our data, not data from any selection, to be written to the clipboard
});

The copy action consists of the following steps:

  1. If the script-triggered flag is set
    If the script-may-access-clipboard flag is unset
    Return false from the copy action, terminate this algorithm
  2. Fire a clipboard event named copy
  3. If the event was not canceled
    Copy the selected contents, if any, to the clipboard. Implementations should create alternate text/html and text/plain clipboard formats when content in a web page is selected.
    else, if the event was canceled
    Call the writing contents to the clipboard algorithm, passing on the DataTransferItemList list items, a clear-was-called flag and a types-to-clear list.
  4. Return true from the copy action

6.1.2 The cut action

Note

When the user initiates a cut action, the implementation fires a clipboard event named cut. In an editable context, if the event is not canceled the action will place the selected data on the clipboard and remove the selection from the document.

The event bubbles and is cancelable.

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

In a non-editable context, or if there is no selection, the cut action does nothing. The implementation fires the event regardless. In this case nothing, the clipboard is not modified except if the script has added entries in the DataTransferItemList and the event is canceled.

Any script which uses the event.clipboardData API to control what the cut event will write to the clipboard also needs to cancel the event. Otherwise, the data the script intends to place on the clipboard will be ignored.

The cut action consists of the following steps:

  1. If the script-triggered flag is set
    If the script-may-access-clipboard flag is unset
    Return false from the cut action, terminate this algorithm
  2. Fire a clipboard event named cut
  3. If the event was not canceled
    If there is a selection in an editable context where cutting is enabled
    1. Copy the selected contents, if any, to the clipboard. Implementations should create alternate text/html and text/plain clipboard formats when content in a web page is selected.
    2. Remove the contents of the selection from the document and collapse the selection.
    3. Queue tasks to fire any events that should fire due to the modification, see interaction with other events for details.
    Else, if there is no selection or the context is not editable
    Return false
    Else, if the event was canceled
    Call the writing contents to the clipboard algorithm, passing on the DataTransferItemList list items, a clear-was-called flag and a types-to-clear list.
  4. Return true from the cut action

6.1.3 The paste action

Note

When a user initiates a paste action, 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 paste action will insert clipboard data in the most suitable format (if any) supported for the given context.

The paste action has no effect 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.

Example 2
document.addEventListener('paste', function(e){
    if(e.clipboardData.types.indexOf('text/html') > -1){
        processDataFromClipboard(e.clipboardData.getData('text/html'));
        e.preventDefault(); // We are already handling the data from the clipboard, we do not want it inserted into the document
    }
});

For the paste action, the script-may-access-clipboard flag depends on an implementation-specific permission mechanism for determining what sites or apps may read from the clipboard. When a paste action is triggered by a script, the implementation must not make clipboard contents available without the user's permission. If the permission has not already been granted, the permission prompt must include the hostname of the document associated with the script thread.

The paste action consists of the following steps:

  1. If the script-triggered flag is set
    If script-may-access-clipboard is unset
    Return false from the paste action, terminate this algorithm
  2. Fire a clipboard event named paste
  3. If the event was not canceled
    If there is a selection or cursor in an editable context where pasting is enabled
    1. Insert the most suitable content found on the clipboard, if any, into the context.
    2. Queue tasks to fire any events that should fire due to the modification, see interaction with other events for details.
    Else
    Return false
    Else, if the event was canceled
    Return false
  4. Return true from the action

6.2 Processing model for event dispatch

To fire a clipboard event of type e,

  1. Let clear-was-called be false
  2. Let types-to-clear be an empty list
  3. Let clipboard-entry be the sequence number of the current clipboard content, or null if the OS clipboard does not support sequence numbers
  4. Let trusted be true if the event is generated by the user agent, false otherwise
  5. Set target as follows:
    If the context is editable:
    Let 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.
    Else, if the context is not editable
    Let target be the focused node, or the body element if no node has focus.
  6. If e is paste

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

    If trusted is true, or the implementation is configured to give script-generated events read access to the OS clipboard

    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:
      Issue 1

      Are these steps necessary? Do we know about native (platform) clipboard implementations that support multiple parts with internal references?

      Issue 2

      This feature is at risk because it's unclear whether it is required, and because it's hard to test in a cross-platform way.

      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

    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

  7. Dispatch an event named e which bubbles and is cancelable and which uses the ClipboardEvent interface, with isTrusted set to trusted, at target.

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

    Issue 3

    Why here? Why not in the HTML spec?

    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: Long-running clipboard reading threads
    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.

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 3
var pasteEvent = new ClipboardEvent('paste');
pasteEvent.clipboardData.items.add('My string', 'text/plain');
document.dispatchEvent(pasteEvent);
Note

Synthetic events do not have default actions. In other words, while the script above will fire a paste event, the data will not actually be pasted into the document.

dictionary ClipboardEventInit : EventInit {
             DataTransfer? clipboardData = null;
};

7.1 Dictionary ClipboardEventInit Members

clipboardData of type DataTransfer, nullable, defaulting to null
A DataTransfer object to hold data and meta data related to the event
[Constructor(DOMString type, optional ClipboardEventInit eventInitDict)]
interface ClipboardEvent : Event {
    readonly        attribute DataTransfer? clipboardData;
};

7.2 Attributes

clipboardData of type DataTransfer, readonly , nullable

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. For synthetic events, the drag data store contains the data added by the script that created the event.

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

8. Writing contents to the clipboard

To update the clipboard contents, follow these steps, given a DataTransferItemList list items, a clear-was-called flag and a types-to-clear list:

If the items list is not empty
  1. Clear the clipboard
  2. For each part in the list,
    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. Place text on clipboard with the appropriate OS clipboard format description
    Otherwise, if data is of a type listed in the mandatory data types list
    Place part on clipboard with the appropriate OS clipboard format description
    Otherwise
    This is left to the implementation..
    Issue 4

    It's not good to leave things up to the implementation. What should happen here?

    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, the items list is empty. Follow these steps to determine whether to clear the clipboard:
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
Issue 5

The "remove specific types from clipboard" feature is at risk. It doesn't seem all that important, and it's unclear if it can be implemented easily across relevant platforms.

9. Integration with other scripts and events

9.1 Event handlers that are allowed to modify the clipboard

Event handlers may write to the clipboard if any of the following is true:

The implementation may allow other trusted event types to modify the clipboard if the implementation authors believe that those event types are likely to express user intention. The implementation may also support configuration that trusts specific sites or apps to modify the clipboard regardless of the origin of the scripting thread.

Synthetic cut and copy events must not modify data on the system clipboard.

9.2 Event handlers that are allowed to read from clipboard

Event handlers may read data from the system clipboard if either of the following is true

Synthetic paste events must not give a script access to data on the real system clipboard.

9.3 Integration with rich text editing APIs

If an implementation supports ways to execute clipboard commands through scripting, for example by calling the document.execCommand() method with the commands "cut", "copy" and "paste", the implementation must trigger the corresponding action, which again will dispatch the associated clipboard event.

These are the steps to follow when triggering copy, cut or paste actions through a scripting API:

  1. Execute the corresponding action synchronously.
  2. Use the action's return value as the return value for the API call.
Note

Copy and cut commands triggered through a scripting API will only affect the contents of the real clipboard if the event is dispatched from an event that is trusted and triggered by the user, or if the implementation is configured to allow this. Paste commands triggered through a scripting API will only fire paste events and give access to clipboard contents if the implementation is configured to allow this. How implementations can be configured to allow read or write access to the clipboard is outside the scope of this specification.

9.4 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 cut and paste actions 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.

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

10. Pasting HTML and multi-part data

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

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

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

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

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

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

Reading from the clipboard

These data types must be exposed by paste events if a corresponding native type exists on the clipboard:

Writing to the clipboard

These data types must be placed on the clipboard with a corresponding native type description if added to a DataTransfer object during copy and cut events.

Warning

Data types untrusted scripts are allowed to write to the clipboard is limited as a security precaution. Untrusted scripts can attempt to exploit security vulnerabilities in local software by placing data known to trigger those vulnerabilities on the clipboard.

13. 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, Chris Mills, "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, Philip Jägenstedt.

A. References

A.1 Normative references

[DOM]
Anne van Kesteren; Aryeh Gregor; Ms2ger; Alex Russell; Robin Berjon. W3C. W3C DOM4. 19 November 2015. W3C Recommendation. URL: http://www.w3.org/TR/dom/
[HTML5]
Ian Hickson; Robin Berjon; Steve Faulkner; Travis Leithead; Erika Doyle Navara; Edward O'Connor; Silvia Pfeiffer. W3C. HTML5. 28 October 2014. W3C Recommendation. URL: http://www.w3.org/TR/html5/
[HTMLEA]
Aryeh Gregor. W3C Editing APIs CG.. HTML Editing APIs. URL: https://dvcs.w3.org/hg/editing/raw-file/tip/editing.html
[HTMLLS]
Ian Hickson. WHATWG.. HTML Living Standard. URL: https://html.spec.whatwg.org/multipage/
[RFC2119]
S. Bradner. IETF. Key words for use in RFCs to Indicate Requirement Levels. March 1997. Best Current Practice. URL: https://tools.ietf.org/html/rfc2119
[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