JavaScript Clipboard API: Read and Write to Clipboard with navigator.clipboard
The 'navigator.clipboard' object in JavaScript provides a way to interact with the clipboard of the user's device. It allows you to read the contents of the clipboard, as well as write data to it.
Here are some common methods and properties of the 'navigator.clipboard' object:
- 'readText()': This method returns a promise that resolves with the text contents of the clipboard.
navigator.clipboard.readText()
.then(text => {
console.log('Clipboard text:', text);
})
.catch(err => {
console.error('Failed to read clipboard contents:', err);
});
- 'writeText(text)': This method writes the given text to the clipboard. It returns a promise that resolves when the text has been successfully written.
const text = 'Hello, clipboard!';
navigator.clipboard.writeText(text)
.then(() => {
console.log('Text written to clipboard:', text);
})
.catch(err => {
console.error('Failed to write text to clipboard:', err);
});
- 'ClipboardEvent.clipboardData': This property provides access to the clipboard data in a 'paste' event. It can be used to read the pasted content.
document.addEventListener('paste', event => {
const clipboardData = event.clipboardData;
const text = clipboardData.getData('text/plain');
console.log('Pasted text:', text);
});
It's important to note that accessing the clipboard in JavaScript requires the user's permission. Modern browsers may prompt the user to grant permission when accessing the clipboard for the first time.
原文地址: https://www.cveoy.top/t/topic/fSJb 著作权归作者所有。请勿转载和采集!