Home >Web Front-end >JS Tutorial >Let's take a look at the JavaScript Asynchronous Clipboard API
In the past few years we could only use document.execCommand
to manipulate the clipboard. However, this manipulation of the clipboard is synchronous and can only read and write to the DOM.
Chrome 66 now supports the new Async Clipboard API as a execCommand
replacement.
This new Async Clipboard API can also use Promise to simplify clipboard events and use them with the Drag-&-Drop API.
writeText()
You can write text to the clipboard. writeText()
is asynchronous, it returns a Promise:
navigator.clipboard.writeText('要复制的文本') .then(() => { console.log('文本已经成功复制到剪切板'); }) .catch(err => { // This can happen if the user denies clipboard permissions: // 如果用户没有授权,则抛出异常 console.error('无法复制此文本:', err); });
You can also use asynchronous functions async
and await
:
async function copyPageUrl() { try { await navigator.clipboard.writeText(location.href); console.log('Page URL copied to clipboard'); } catch (err) { console.error('Failed to copy: ', err); } }
Like copying, you can read text from the clipboard by calling readText()
. This function also returns a Promise:
navigator.clipboard.readText() .then(text => { console.log('Pasted content: ', text); }) .catch(err => { console.error('Failed to read clipboard contents: ', err); });
For consistency, here is the equivalent asynchronous function:
async function getClipboardContents() { try { const text = await navigator.clipboard.readText(); console.log('Pasted content: ', text); } catch (err) { console.error('Failed to read clipboard contents: ', err); } }
There are plans to launch a new event that detects clipboard changes, but at this time It's better to use the "paste" event. It lends itself well to the new asynchronous method for reading clipboard text:
document.addEventListener('paste', event => { event.preventDefault(); navigator.clipboard.readText().then(text => { console.log('Pasted text: ', text); }); });
Clipboard access has always caused security issues for browsers. Without the proper permissions, the page could silently copy any malicious content to the user's clipboard, with disastrous results when pasted. Imagine a web page that silently copies rm -rf /
or unzips the bomb image to the clipboard.
Allowing web pages to read the clipboard without restrictions is more troublesome. Users often copy sensitive information such as passwords and personal details to the clipboard, which can then be read from any page without the user even noticing.
Like many new APIs, navigator.clipboard
only supports pages served over HTTPS. To prevent abuse, clipboard access is only allowed when the page is in the active tab. Pages in the active tab can write to the clipboard without requesting permission, but reading from the clipboard always requires permission.
To make it easier, two new permissions for copy and paste have been added to the Permissions API. clipboard-write permission is automatically granted to the page when it is in the active tab. When you read data from the clipboard, you must ask for the clipboard-read permission.
{ name: 'clipboard-read' } { name: 'clipboard-write' }
Like anything else using the permissions API, you can check whether your app has permission to interact with the clipboard:
navigator.permissions.query({ name: 'clipboard-read' }).then(permissionStatus => { // permissionStatus.state 的值是 'granted'、'denied'、'prompt': console.log(permissionStatus.state); // 监听权限状态改变事件 permissionStatus.onchange = () => { console.log(permissionStatus.state); }; });
The following is the clipboard This is where the "async" part of the Board API really comes in handy: attempts to read or write clipboard data will automatically prompt the user for permission if it has not already been granted. Because the API is Promise-based, if the user denies clipboard permission, the Promise will be rejected so the page can respond appropriately.
Because Chrome only allows clipboard access when the page is the current active tab, you will find that some of the examples here will not run correctly if you paste directly into DevTools, because DevTools itself is active at this time tab (the page is not the active tab). There is a trick: we need to defer the clipboard access using setTimeout, and then quickly click inside the page to get focus before calling the function:
setTimeout(async () => { const text = await navigator.clipboard.readText(); console.log(text); }, 2000);
Before the introduction of the asynchronous clipboard API , we mixed different copy and paste implementations in web browsers.
In most browsers, you can use document.execCommand('copy')
and trigger the browser's own copy and paste document.execCommand('paste')
. If the text to be copied is a string that doesn't exist in the DOM, we have to insert it into the DOM and select it:
button.addEventListener('click', e => { const input = document.createElement('input'); document.body.appendChild(input); input.value = text; input.focus(); input.select(); const result = document.execCommand('copy'); if (result === 'unsuccessful') { console.error('Failed to copy text.'); } })
Again, here's how you can browse without support for the new Async Clipboard API The pasted content is processed in the server:
From: https://github.com/justjavac/the-front-end-knowledge-you-may-not-know/issues/23
document.addEventListener('paste', e => { const text = e.clipboardData.getData('text/plain'); console.log('Got pasted text: ', text); })
In Internet Explorer, we can also access the clipboard through window.clipboardData
. If access occurs within a user gesture (e.g. a click event) - part of requesting permissions in a responsible manner - the permission prompt is not shown.
While supporting all browsers, it is a good idea to use feature detection to take advantage of the asynchronous clipboard. You can detect support for the Async Clipboard API by checking navigator.clipboard
:
document.addEventListener('paste', async e => { let text; if (navigator.clipboard) { text = await navigator.clipboard.readText() } else { text = e.clipboardData.getData('text/plain'); } console.log('Got pasted text: ', text); });
正如你可能已经注意到的那样,这篇文章只涵盖了 navigator.clipboard
的文本部分。规范中有更多的通用 read()
和 write()
方法,但是这些会带来额外的实现复杂性和安全性问题(请记住那些图像炸弹?)。目前,Chrome 正在推出更简单的 API 文本部分。
出自:justjavac
推荐教程:《javascript基础教程》
The above is the detailed content of Let's take a look at the JavaScript Asynchronous Clipboard API. For more information, please follow other related articles on the PHP Chinese website!