preface

Recently, I made a requirement about this aspect. It is my first time to make a content about this piece. Now I will sort out the relevant implementation. JS can access the paste board in the following ways

  • A native methodexecCommand
  • A native methodClipboard
  • Third-party librariesclipboard.js(recommended)

After investigation and practice, the third party library clipboard.js is finally selected to realize their own needs

document.execCommand()

Deprecated: This feature is obsolete. Although it may still work in some browsers, its use is discouraged as it can be removed at any time. Try to avoid it.

This is a reminder from the MDN documentation, which doesn’t even give details on how to use it. Here’s a quick look at the use of execCommand

<input type="text" id="input" value="123">
<button onclick="copy()">copy</button>
<script>
  function copy() {
    const inputEle = document.querySelector('#input');
    inputEle.select();
    // Must be manually invoked by the user
    document.execCommand('copy');
    // cut, delete (delete the selected element)
    // document.execCommand('cut');
  }
</script>
Copy the code

Commands such as copy and cut return a Boolean value to determine whether this function is available in the browser.

For security reasons, the document.execCommand(‘paste’) operation has been disabled.

If you want to use the execCommand method without having editable areas on your page, you can use the following tricks

<button onclick="Copy2Clipboard (' Hide copy!! ')">copy</button>
<script>
  function copy2Clipboard(content) {
    const dom = document.createElement('input');
    dom.value = content;
    document.body.appendChild(dom);
    dom.select();
    document.execCommand('copy');
    document.body.removeChild(dom);
  };
</script>
Copy the code

After investigation, execCommand has the following defects

  1. They’re not flexible enough to operateinput.textareaOr havecontenteditableElement of the attribute
  2. execCommandIf you copy/paste a large amount of data, the page will stall.
  3. Some browsers also pop up a box asking for permission, and the page stops responding before the user makes a choice.

Clipboard

Clipboard The Clipboard API provides the ability to respond to Clipboard commands with asynchronous reads and writes to the system Clipboard. Access to clipboard content after obtaining Permissions from the Permissions Permissions API; Clipboard content is not allowed to be read or changed if the user has not granted permission. The API is designed to replace clipboard access using Document.execcommand (). You can use the navigator. Clipboard property to check whether the browser supports the API, or not if you return undefined

Read paste board

<button onclick="readClip()">readClip</button>
<script>
  function readClip() {
    // Read text
    navigator.clipboard.readText().then(clipText= > console.log(clipText));
    // navigator.clipboard.read() reads data, such as images
  }
</script>
Copy the code
  1. Chrome stipulates that only HTTPS pages can use this API. However, the development environment is fine
  2. There are two permissions associated with the stickboard,clipboard-write(Write permission) andclipboard-read(Read permission). The write permission is automatically granted to the script, while the read permission must be explicitly approved by the user because it involves user privacy.

You can perform the following operations to check whether you have read and write permissions

navigator.permissions.query({ name: 'clipboard-write' });
Copy the code

Write paste board

<button onclick="copy2clip()">copy2clip</button>
<script>
  function readClip() {
    // Write text
    navigator.clipboard.writeText("Write to the paste board").then(() = > console.log("Write to clipboard successfully"));
    / / the navigator. Clipboard. Write write any data
  }
</script>
Copy the code

Clipboard. Js library

Method of copying text to clipboard, no Flash, no frame. When compressed, it’s only 3KB

The installation

/ / the node installation
npm install clipboard --save
/ / the CDN
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/clipboard.min.js"></script>
Copy the code

Basic usage

Copy/cut the text of another element

<! -- Target provides copied text -->
<input id="foo" value="https://github.com/zenorocha/clipboard.js.git">
<! -- Support copying other element content -->
<! -- <div id="foo">
<! -- If multiple targets exist, copy first target -->

<! -- Trigger duplicates the function of the Trigger, Trigger can be other elements, can be clicked to Trigger -->
<! -- data-clipboard-target Set target, syntax same as JQuerry -->
<button class="btn" data-clipboard-target="#foo">copy</button>
<! -- Set the trigger to copy by setting the data-clipboard-action property.
<! -- Only input elements (input, textarea, etc.) support clipping -->
<button class="btn" data-clipboard-target="#foo" data-clipboard-action="cut">cut</button>

<script>
  // Check whether the browser supports clipboard returns a Boolean value,
  // If not, you can hide the copy/cut button.
	ClipboardJS.isSupported()
  // Listen on the selected element with the same syntax as JQuerry
  var clipboard = new ClipboardJS('.btn');
  // called after successful replication
  clipboard.on('success'.function (e) {
    console.info('Action:', e.action);
    console.info('Text:', e.text);
    console.info('Trigger:', e.trigger);
  });
 // called after replication failure
  clipboard.on('error'.function (e) {
    console.error('Action:', e.action);
    console.error('Trigger:', e.trigger);
  });
  // You can provide feedback to the user by listening on both events
</script>
Copy the code

Copy the value of its own property

Make it copy itself by setting the data-clipboard-text property

<button class="btn" data-clipboard-text="Contents of its own attributes.">copySelf</button>
Copy the code

Advanced usage

Dynamically set target

You need to return a DOM node

<button class="btn" data-clipboard-target="#foo">copy</button>
<div>1234</div>
<script>
  var clipboard = new ClipboardJS('.btn', {
    // Use the next sibling of trigger as target
    // The data-clipboard-targe attribute does not take effect
    target: (trigger) = > trigger.nextElementSibling
  });
</script>
Copy the code

Dynamically set the returned text

You need to return a string

<button class="btn">copy</button>
<script>
  new ClipboardJS('.btn', {
    text: () = > "Dynamic text content"
  });
</script>
Copy the code

Set the container

On this piece of their own is not very understand what role, now the official interpretation of the translation attached below

To use in Bootstrap Modals or any other library that changes focus, you need to set the focus element to the container value.

new ClipboardJS('.btn', {
    container: document.getElementById('modal')});Copy the code

Clean up the created objects

If you want to manage the DOM life cycle more precisely, you can use the destroy method to clean up the objects you create

clipboard.destroy();
Copy the code

Clear clipboard contents

The browser does not provide an interface to clean up the clipboard. If a site needs to clean up after using clipboard content, it can write data again

// ...
input.value = ' '; // The input value must have a value, not an empty string
input.select();
document.execCommand('copy')
// Or use clipboard
navigator.clipboard.writeText(' ');
// 
new ClipboardJS('.btn', {
    text: () = > "" // Must have a value, not an empty string
  });
Copy the code

conclusion

Document. ExecCommand is really not that comfortable to use, even the official has abandoned it, so we should try to avoid using this API in future development, and try to use the API Clipboard. As for Clipboard.js, although it has dependencies on execCommand and Selection, I personally have no problem using it, and I still recommend it.

reference

document.execCommand

Clipboard API​