Copy and paste operations are required in daily service development scenarios, such as adding copyright information after copying or clicking Copy. The following are several implementation schemes.

Clipboard API

The Clipboard API provides the ability to respond to Clipboard commands (cut, copy, and paste) and asynchronously read and write to the system Clipboard. Access to clipboard content after obtaining Permissions from the Permissions API (Permissions API); If the user has not granted permission, the clipboard content is not allowed to be read.

You can access the clipboard using the global navigator.clipboard.

The navigator. clipboard property returns the ClipBoard object through which all operations are performed.

The Clipboard object provides four methods for reading and writing the Clipboard. They are both asynchronous methods that return Promise objects.

read( )methods

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

The read() 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.

The ClipboardItem object represents a separate clipping item, each of which has a types attribute and a getType() method.

The clipboardItem. types property returns an array of available MIME types for the clipping item. For example, a clipping item can be pasted in HTML or plain text. Then it has two MIME types (text/ HTML and text/plain).

The clipboardItem.getType (type) method is used to read the data of the clip item and return a Promise object. This method takes the MIME type of the clipitem as an argument and returns data of that type. This argument is required or an error will be reported.

Example:

// Obtain permission
navigator.permissions
.query({
  name: 'clipboard-read'
})
.then(result= > {
  if (result.state == 'granted' || result.state == 'prompt') {
	// Read the clipboard
	navigator.clipboard.read().then(data= > {
	  console.log(data)
	})
  } else {
	alert('Please allow to read clipboard! ')}})Copy the code

readText( )methods

The readText() method reads text content from the clipboard. This method requires explicit permission from the user.

Example:

// Obtain permission
navigator.permissions
.query({
  name: 'clipboard-read'
})
.then(result= > {
  if (result.state == 'granted' || result.state == 'prompt') {
	// Read the clipboard
	navigator.clipboard.readText().then(text= > {
	  console.log(text)
	})
  } else {
	alert('Please allow to read clipboard! ')}})Copy the code

write( )methods

The write() method can write arbitrary data to the clipboard, either text or binary. This method does not require user permission.

The write() method takes an instance of ClipboardItem as an argument representing the data to be written to the clipboard.

Example:

// Write a picture
const imgURL = 'https://dummyimage.com/300.png'
const data = await fetch(imgURL)
const blob = await data.blob()
await navigator.clipboard.write([
	new ClipboardItem({
	  [blob.type]: blob
	})
])
Copy the code

Note that Chrome currently only supports writing PNG images.

writeText( )methods

The writeText() method writes text content to the clipboard. This method does not require user permission.

Example:

navigator.clipboard.writeText('Write clipboard text content')
Copy the code

Security restrictions

This API has more security restrictions because users can put sensitive data (such as passwords) on the clipboard and allow scripts to read it at will.

First, Chrome dictates that only HTTPS pages can use the API. However, the development environment (Localhost) allows the use of non-encryption protocols.

Second, you need to explicitly ask the user’s permission when making the call. The Permissions implementation uses the Permissions API, and there are two Permissions associated with the clipboard: clipboard-write and clipboard-read. Write permission is automatically granted to the script, while read permission must be given with the explicit consent of the user. That is, when you write to the clipboard, the script can do it automatically, but when you read the clipboard, the browser will pop up a dialog asking if the user agrees to read it.

Document.execCommand()

This API is deprecated and not recommended, but check it out for compatibility.

The document.execcommand () method is used to manipulate the contents of an editable area.

document.execCommand('copy')

Document. execCommand(‘copy’) implements the copy operation

Example:

<input id="copyContent" value="Content to be copied">
<button id="copyBtn">Let me copy</button>
Copy the code
const copyBtn = document.querySelector('#copyBtn');
const copyContent = document.querySelector('#copyContent');
// The copy operation is placed in the event listener function and triggered by the user (for example, when the user clicks a button).
copyBtn.addEventListener('click'.() = > {
	copyContent.select();
	document.execCommand('copy');
})
Copy the code

document.execCommand('paste')

Document. execCommand(‘paste’) implements the paste operation

Example:

<input id="paste" placeholder="Paste">
Copy the code
const pasteText = document.querySelector('#paste');
pasteText.focus();
document.execCommand('paste');
Copy the code

ExecCommand (‘paste’) execCommand(‘paste’)

clipboard.js

In addition to using native JS, you can also use third-party libraries such as clipboard.js to copy text to the clipboard.

The installation

NPM install

npm install clipboard --save
Copy the code

Script tag introduction

<script src="dist/clipboard.min.js"></script>
Copy the code

use

Use one element as a trigger to copy the text of another element, passing a DOM selector, HTML element, or HTML element list to instantiate it.

2. Add the data-clipboard-target attribute to the trigger element. The value of this attribute is an element selector that matches another element that needs to be copied.

Example:

<div id="copyContent">Content that needs to be copied</div>
<button id="copyBtn" data-clipboard-target="#copyContent">Click on the copy</button>
Copy the code
/ / triggers
var clipboard = new ClipboardJS('#copyBtn')

clipboard.on('success'.function (e) {
  console.log('Copy succeeded! ')
  console.log('Manipulate text content :', e.text)
  console.log('DOM element that triggers the operation :', e.trigger)
  e.clearSelection()
})

clipboard.on('error'.function (e) {
  console.log('Replication failed')
  console.log('DOM element that triggers the operation :', e.trigger)
})
Copy the code

Alternatively, the data-clipboard-action attribute can be defined as copy or cut on the trigger element to specify whether the action is copy or cut. If this attribute is omitted, the default is copy. A value of cut applies only to input or Textarea elements.

<input id="copyContent" value="What needs to be copied"/>
<button id="copyBtn" data-clipboard-target="#copyContent" data-clipboard-action="cut">Click on the shear</button>
Copy the code
/ / triggers
var clipboard = new ClipboardJS('#copyBtn')

clipboard.on('success'.function (e) {
  console.log('Copy succeeded! ')
  console.log('Manipulate text content :', e.text)
  console.log('DOM element that triggers the operation :', e.trigger)
  e.clearSelection()
})

clipboard.on('error'.function (e) {
  console.log('Replication failed')
  console.error('DOM element that triggers the operation :', e.trigger)
})
Copy the code

If you define the data-clipboard-text attribute on the trigger element, you do not need another element to copy its contents. The value of the data-clipboard-text attribute is what needs to be copied.

Example:

<button id="copyBtn" data-clipboard-text="What needs to be copied">Click on the copy</button>
Copy the code
/ / triggers
var clipboard = new ClipboardJS('#copyBtn')

clipboard.on('success'.function (e) {
  console.log('Copy succeeded! ')
  console.log('Manipulate text content :', e.text)
  console.log('DOM element that triggers the operation :', e.trigger)
  e.clearSelection()
})

clipboard.on('error'.function (e) {
  console.log('Replication failed')
  console.error('DOM element that triggers the operation :', e.trigger)
})
Copy the code

Event listeners

Copy the event

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

Example:

document.addEventListener('copy'.function (event) {
  alert('Trigger replication event')
  // Clipboard data
  console.log(event.clipboardData)
})
Copy the code

clipboardDataobject

In the example above, the clipboardData property of the event object contains the clipboardData. It is an object with the following properties and methods.

setData( )methods

Event. The clipboardData. SetData (type, data) : in the Event of the cut and copy to modify the clipboard data, you need to specify the data type.

Example:

<div id="copyContent">
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dignissimos expedita temporibus facere mollitia nemo at voluptatibus dicta commodi neque iusto nesciunt earum suscipit deserunt delectus numquam cum nulla libero fugit.
</div>
Copy the code
var copyContent = document.querySelector('#copyContent');
copyContent.addEventListener('copy'.(event) = > {
	const selection = document.getSelection();
	// Copy the text content to uppercase
	event.clipboardData.setData('text/plain', selection.toString().toUpperCase());
	event.preventDefault();
});
Copy the code
getData( )methods

Event. The clipboardData. GetData (type) : in the Event of an paste obtain clipboard data, you need to specify the data type.

Example:

document.addEventListener('paste'.function (event) {
  alert('Trigger paste event')
  // Get pasted text content
  var text = event.clipboardData.getData('text/plain');
  console.log('Paste content:',text)
})
Copy the code
itemsattribute

Event. The clipboardData. Items: a similar array of objects, includes all clip-book items, but usually only one clip.

The cut event

The cut Event is triggered when the user cuts and is handled exactly like a copy Event, retrieving the cut data from the Event. ClipboardData property.

Example:

document.addEventListener('cut'.function () {
	alert('Trigger clipping event')
	// Clipboard data
	console.log(event.clipboardData)
})
Copy the code

Paste the event

When you paste clipboard data, the paste event is triggered.

Example:

document.addEventListener('paste'.async (e) => {
  e.preventDefault();
  // Get the text data in the clipboard
  const text = await navigator.clipboard.readText();
  console.log('Paste text:', text);
});
Copy the code

Related to the sample

  • Click on the copy

  • Read the clipboard picture

  • Copy additional copyright information

Refer to the article

Web one-click copy and paste

Summary of clipboard copy-paste operations

JavaScript copies content to the clipboard

Clipboard operation Clipboard API tutorial

Copy and paste plugin – use of clipboard.js