JavaScript 粘贴事件、拷贝事件、获取拷贝的内容、将文本复制到剪贴板
// 监听粘贴事件
window.addEventListener('paste', pasteHandler)
function pasteHandler(event) {
event = event || window.event
const clipdata = event.clipboardData || window.clipboardData
const value = clipdata.getData('text/plain')
console.log(value)
}
// 监听拷贝事件,并将内容改为自定义的值
window.addEventListener('copy', copyHandler)
function copyHandler(event) {
event = event || window.event
event.clipboardData?.setData('text/plain', 'hello world')
event.preventDefault()
}
// -----------------------
// 获取拷贝的内容
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)
}
}
// 将文本复制到剪贴板
async function copyPageUrl() {
try {
await navigator.clipboard.writeText('hello world222')
} catch (err) {
console.error('Failed to copy: ', err)
}
}
setTimeout(() => {
copyPageUrl()
getClipboardContents()
}, 2000)