document.execCommand 已被废弃,不再要求浏览器支持
所以下面写了两种写法
function copyMsg() {
const username = 'username'
const password = 'password'
const msg = `
网址:<a href="${ location.origin }">${ location.origin }</a>/<br />
登录名:${ username }<br />
密码:${ password }
`
try {
// 传统 document.execCommand 方法 MDN 已废弃
const save = function(e) {
e.clipboardData.setData('text/html', msg)
e.preventDefault()
}
document.addEventListener('copy', save, { once: true })
document.execCommand('copy')
} catch(e) {
// 新标准 注意此处是异步的
const item = new window.ClipboardItem({
"text/html": new Blob([msg], { type: "text/html" })
});
navigator.clipboard.write([item]).then(function() {
console.log('Async: Copying to clipboard was successful!');
}, function(err) {
console.error('Async: Could not copy text: ', err);
});
}
}
copyMsg()