In daily business development, such as adding copyright information after copying, clicking copy, and other scenes that need to be copied and pasted, the following are several implementation solutions.
Clipboard API
Clipboard API provides the ability to respond to clipboard commands (cut, copy and paste) and asynchronously read and write the system clipboard. after obtaining the permission from the permission API (1613188c018309 Permissions API ) can the contents of the clipboard be accessed; if the user does not grant permission, the contents of the clipboard are not allowed to be read.
You can use the global Navigator.clipboard to access the clipboard.
Navigator.clipboard property returns Clipboard object, all operations are performed through this object.
Clipboard The object provides four methods for reading and writing the clipboard. They are all asynchronous methods that return Promise objects.
read() method
read()
method can read arbitrary data from the clipboard, which can be text data or binary data (such as pictures). This method requires explicit permission from the user.
read()
method returns a Promise
object. Once the state of the object becomes resolved
, an array can be obtained, and each array member is an instance of the ClipboardItem
ClipboardItem object represents a single clip item, each clip item has types
attribute and getType( )
method.
ClipboardItem.types
property returns an array. The members in it are the MIME
types available for the clip item. For example, a clip item can be HTML
format or in plain text format. Then it has two MIME
types ( text/html
and text/plain
) .
ClipboardItem.getType(type)
method is used to read the data of the clip item and returns a Promise
object. This method accepts the MIME
type of the clip item as a parameter, and returns the data of this type. This parameter is required, otherwise an error will be reported.
example :
//获取权限
navigator.permissions
.query({
name: 'clipboard-read'
})
.then(result => {
if (result.state == 'granted' || result.state == 'prompt') {
//读取剪贴板
navigator.clipboard.read().then(data => {
console.log(data)
})
} else {
alert('请允许读取剪贴板!')
}
})
readText() method
readText()
method can read text content from the clipboard. This method requires explicit permission from the user.
example :
//获取权限
navigator.permissions
.query({
name: 'clipboard-read'
})
.then(result => {
if (result.state == 'granted' || result.state == 'prompt') {
//读取剪贴板
navigator.clipboard.readText().then(text => {
console.log(text)
})
} else {
alert('请允许读取剪贴板!')
}
})
write() method
write()
method can write arbitrary data to the clipboard, which can be text data or binary data. This method does not require user permission.
write()
method accepts a ClipboardItem instance as a parameter, which represents the data written to the clipboard.
example :
//写入一张图片
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
})
])
Note that the Chrome browser currently only supports writing images in PNG format.
writeText() method
writeText()
method can write text content to the clipboard. This method does not require user permission.
example :
navigator.clipboard.writeText('写入剪贴板文本内容')
Security restrictions
Since users may put sensitive data (such as passwords) on the clipboard, allowing scripts to read them arbitrarily will cause security risks, so this API has more security restrictions.
First of all, Chrome browser stipulates that only HTTPS protocol pages can use this API. However, the development environment ( localhost
) allows the use of non-encrypted protocols.
Secondly, the user's permission needs to be clearly obtained when calling. The specific implementation of permissions uses Permissions API , and there are two permissions related to the clipboard: clipboard-write
(write permission) and clipboard-read
(read permission). The "write permission" is automatically granted to the script, and the "read permission" must be explicitly granted by the user. In other words, the script can be automatically completed when writing to the clipboard, but when reading the clipboard, the browser will pop up a dialog box asking whether the user agrees to read.
Document.execCommand()
This API has been deprecated and it is not recommended to use it, but for compatibility, let’s check it out.
document.execCommand()
method is used to manipulate the content of the editable area.
document.execCommand('copy')
document.execCommand('copy')
realizes the copy operation
Example:
<input id="copyContent" value="需要被复制内容">
<button id="copyBtn">点我复制</button>
const copyBtn = document.querySelector('#copyBtn');
const copyContent = document.querySelector('#copyContent');
// 复制操作要放在事件监听函数里面,由用户触发(比如用户点击按钮)。
copyBtn.addEventListener('click', () => {
copyContent.select();
document.execCommand('copy');
})
document.execCommand('paste')
document.execCommand('paste')
realizes paste operation
Example:
<input id="paste" placeholder="粘贴">
const pasteText = document.querySelector('#paste');
pasteText.focus();
document.execCommand('paste');
Chrome and Firefox do not support document.execCommand('paste')
clipboard.js
In addition to using native JS, you can also use some third-party libraries, such as clipboard.js to realize the operation of copying text to the clipboard.
Install
npm install clipboard --save
<script src="dist/clipboard.min.js"></script>
use
1. To use one element as a trigger to copy the text of another element, you need to pass the DOM
selector, HTML
element or HTML
element list to instantiate it.
data-clipboard-target
attribute on the trigger element. The attribute value is an element selector to match another element that needs to be copied.
Example:
<div id="copyContent">需要被复制的内容</div>
<button id="copyBtn" data-clipboard-target="#copyContent">点击复制</button>
//触发器
var clipboard = new ClipboardJS('#copyBtn')
clipboard.on('success', function (e) {
console.log('复制成功!')
console.log('操作文本内容:', e.text)
console.log('触发操作的DOM元素:', e.trigger)
e.clearSelection()
})
clipboard.on('error', function (e) {
console.log('复制失败')
console.log('触发操作的DOM元素:', e.trigger)
})
In addition, the trigger element can also define the data-clipboard-action
attribute as copy
or cut
to specify whether the operation is to copy or cut. If this attribute is omitted, the default is to copy. When the value is cut
, it only applies to input
or textarea
elements.
<input id="copyContent" value="需要被复制的内容"/>
<button id="copyBtn" data-clipboard-target="#copyContent" data-clipboard-action="cut">点击剪切</button>
//触发器
var clipboard = new ClipboardJS('#copyBtn')
clipboard.on('success', function (e) {
console.log('复制成功!')
console.log('操作文本内容:', e.text)
console.log('触发操作的DOM元素:', e.trigger)
e.clearSelection()
})
clipboard.on('error', function (e) {
console.log('复制失败')
console.error('触发操作的DOM元素:', e.trigger)
})
If you define the data-clipboard-text
attribute on the trigger element, you do not need another element to copy its content. data-clipboard-text
attribute value is what needs to be copied.
Example:
<button id="copyBtn" data-clipboard-text="需要被复制的内容">点击复制</button>
//触发器
var clipboard = new ClipboardJS('#copyBtn')
clipboard.on('success', function (e) {
console.log('复制成功!')
console.log('操作文本内容:', e.text)
console.log('触发操作的DOM元素:', e.trigger)
e.clearSelection()
})
clipboard.on('error', function (e) {
console.log('复制失败')
console.error('触发操作的DOM元素:', e.trigger)
})
Event monitoring
copy event
When the user puts data into the clipboard, the copy
event will be triggered.
Example:
document.addEventListener('copy', function (event) {
alert('触发复制事件')
//剪切板数据
console.log(event.clipboardData)
})
clipboardData object
In the above example, the clipboardData property of the event object contains the clipboard data. It is an object with the following properties and methods.
setData( )
Method
Event.clipboardData.setData(type, data)
: To cut
and copy
events, the data type needs to be specified.
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>
var copyContent = document.querySelector('#copyContent');
copyContent.addEventListener('copy', (event) => {
const selection = document.getSelection();
//复制文本内容转大写
event.clipboardData.setData('text/plain', selection.toString().toUpperCase());
event.preventDefault();
});
getData( )
method
Event.clipboardData.getData(type)
: To paste
event, the data type needs to be specified.
Example:
document.addEventListener('paste', function (event) {
alert('触发粘贴事件')
//获取粘贴文本内容
var text = event.clipboardData.getData('text/plain');
console.log('粘贴内容:',text)
})
items
attributes
Event.clipboardData.items
: An array-like object that contains all clip items, but usually there is only one clip item.
cut event
cut
event is triggered when the user performs a cutting operation. Its processing is exactly the same as the copy
event, and the cut data Event.clipboardData
Example:
document.addEventListener('cut', function () {
alert('触发剪切事件')
//剪切板数据
console.log(event.clipboardData)
})
paste event
When the user uses the clipboard data to paste, the paste
event will be triggered.
Example:
document.addEventListener('paste', async (e) => {
e.preventDefault();
//获取剪贴板里的文本数据
const text = await navigator.clipboard.readText();
console.log('粘贴文本: ', text);
});
Related examples
Reference article
Clipboard copy and paste operation summary
JavaScript copy content to clipboard
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。