The browser can manipulate the clipboard in three ways:

  1. Document. ExecCommand () (deprecated)
  2. Clipboard API
  3. Copy, cut, and paste events

A, document. ExecCommand ()

Reference link: developer.mozilla.org/zh-CN/docs/…

This method allows you to run commands to manipulate elements in an editable content area. This method returns a Boolean value, false indicating that the operation is not supported or enabled.

  1. copy

    Select the text, then call document.execcommand (‘copy’), and the selected text will be copied into the clipboard

    const text = document.querySelector('#text');
    text.select();
    document.execCommand('copy');
    Copy the code
  2. shear

    Select the text, then call document.execcommand (‘cut’), and the selected text will be cut into the clipboard

  3. paste

    Calling document.execcommand (‘paste’) prints the contents of the clipboard into the current focus element

    const output = document.querySelector('#output');
    output.focus();
    document.execCommand('paste');
    Copy the code

PS: attention! This feature is outdated. Although it may still work in some browsers, it is not recommended because it can be removed at any time. Try to avoid it.

Second, the Clipboard API

Reference link: developer.mozilla.org/zh-cn/docs/…

The traditional document.execcommand () has some flaws:

  1. Only the selected content can be copied to the clipboard, nothing else can be written to the clipboard
  2. It is a synchronous operation and the page may stagnate when there is a large amount of data

The Clipboard API is a browser vendor’s asynchronous solution to this problem. All of its operations are asynchronous, return Promise objects, and do not cause the page to stall. Moreover, it can put any content (such as pictures) into the clipboard

The system clipboard is exposed in the global property navigator.clipboard. If the navigator.clipboard property returns undefined, the current browser does not support this API

For security reasons, this API has the following security restrictions:

  1. Chrome specifies that only HTTPS pages can use this API (except localhost)
  2. If the user does not timely usePermissions APIGrant corresponding permissions and"clipboard-read""clipboard-write"Permissions, callClipboardObject method will not succeed

Methods:

read()

Read clipboard data, either text data or binary data (such as images). This method requires explicit permission from the user.

This method returns a Promise object. Once the object’s state is resolved, you can get an array with each array member being an instance of the ClipboardItem object.

readText()

Read text data from the clipboard. This method requires explicit permission from the user.

This method returns a Promise object. Once the object’s state becomes Resolved, you can get the text data from the clipboard.

write()

Used to write arbitrary data to the clipboard, either text or binary.

This method takes an instance of ClipboardItem as an argument representing the data written to the clipboard.

writeText()

Used to write text content to the clipboard.

This method takes a string as an argument representing the data written to the clipboard.

Example: Copy and paste text data using writeText() and readText() :

<p>hello world</p>
<button id="btn-copy">copy text</button>
<button id="btn-paste">copy text</button>
<script>
  const copyBtn = document.querySelector('#btn-copy');
  copyBtn.addEventListener(
    'click'.async function () {
      try {
        // Edit the text in the p tag and write it to the clipboard
        await navigator.clipboard.writeText(
          `The ${document.querySelector('p').textContent}! `
        );
      } catch (e) {
        console.error('Failed to copy: ', e); }},false
  );

  const pasteBtn = document.querySelector('#btn-paste');
  pasteBtn.addEventListener(
    'click'.async function () {
      try {
        // Reads the text in the clipboard
        const text = await navigator.clipboard.readText();
        console.log(text);
      } catch (e) {
        console.error('Failed to read clipboard content: ', e); }},false
  );
</script>
Copy the code

Copy, cut, and paste events

  1. Copy the event

    When a user adds data to the clipboard, the Copy event is triggered

    <p id="text"< p style = "max-width: 100%; clear: both;<script>
      const text = document.querySelector('#text');
      text.addEventListener(
        'copy'.function (e) {
          // Get the text copied by the user
          const selectText = document.getSelection().toString();
          console.log(selectText)
          // Modify the text copied by the user
          e.clipboardData.setData('text/plain'.'Picking up all the cold branches and refusing to live, lonely sandbar cold');
          e.preventDefault();
        },
        false
      );
    </script>
    Copy the code

    The event object in the example above has a clipboardData property, which is an object with the following properties and methods:

    • Event.clipboardData.setData(type, data): Modifies clipboard data. The data type needs to be specified.
    • Event.clipboardData.getData(type): Gets clipboard data. The data type must be specified.
    • Event.clipboardData.clearData([type]): Clears clipboard data. You can specify the data type. If no type is specified, all types of data are cleared.
    • Event.clipboardData.items: an array-like object that contains all the clipping items, but usually only one.
  2. The cut event

    When a user cuts data, the cut event is triggered

  3. Paste the event

    When you paste clipboard data, the paste event is triggered

    document.addEventListener('paste'.async (e) => {
      // Intercept paste operation by Clipboard API print Clipboard content
      e.preventDefault();
      const text = await navigator.clipboard.readText();
      console.log('Pasted text: ', text);
    });
    Copy the code