function copyTextToClipboard(text) {
// 如果支持 navigator.clipboard 时使用
if (navigator.clipboard) {
navigator.clipboard.writeText(text);
return true; // 我们不理会异步,假装成功
}
// 当浏览器不支持 navigator.clipboard 时使用
var textArea = document.createElement("textarea");
textArea.value = text;
// Avoid scrolling to bottom
textArea.style.top = "0";
textArea.style.left = "0";
textArea.style.position = "fixed";
document.body.appendChild(textArea);
textArea.focus();
textArea.select();
try {
return document.execCommand('copy');
} catch (err) {
return false;
} finally {
document.body.removeChild(textArea);
}
}
在 Console 中,写入剪切板
Firefox
window.navigator.clipboard.writeText(123)
Promise { <state>: "rejected", <reason>: DOMException }
<state>: "rejected"
<reason>: DOMException: Clipboard write was blocked due to lack of user activation.
在 Firefox 中,需要进入 Brower Console 界面:Ctrl+Shift+J,但是这不能针对页面执行代码。
# TODO 在 Console 中,复制到剪切板
我们经常在 Console 中执行代码,以快捷地完成任务,但是复制剪切板不可用。使用 tampermonkey 勉强解决问题。
参考文献
Browser Console – Firefox Developer Tools | MDN
javascript – DOMException on calling navigator.clipboard.readText() – Stack Overflow