起因
最近幫同事實現了一個小功能——復制文本到剪貼板,主要參考了前端大神阮一峰的博客,根據 navigator.clipboard
返回的 Clipboard 對象的方法 writeText()
寫文本到剪貼板。在本地測試時一切正常,到了測試環境卻提示:
Uncaught (in promise) TypeError: Cannot read property 'writeText' of undefined
at HTMLInputElement.<anonymous>
在 Chrome 的 DevTools 控制台下執行 navigator.clipboard
返回 undefined
,經查找資料發現是瀏覽器禁用了非安全域的 navigator.clipboard
對象,哪些地址是安全的呢?
安全域包括本地訪問與開啟TLS安全認證的地址,如 https
協議的地址、127.0.0.1
或 localhost
。
所以本文就是作一個兼容寫法,在安全域下使用 navigator.clipboard
提升效率,非安全域退回到 document.execCommand('copy');
保證功能可用。
腳本內容
function copyToClipboard(textToCopy) {
// navigator clipboard 需要https等安全上下文
if (navigator.clipboard && window.isSecureContext) {
// navigator clipboard 向剪貼板寫文本
return navigator.clipboard.writeText(textToCopy);
} else {
// 創建text area
let textArea = document.createElement("textarea");
textArea.value = textToCopy;
// 使text area不在viewport,同時設置不可見
textArea.style.position = "absolute";
textArea.style.opacity = 0;
textArea.style.left = "-999999px";
textArea.style.top = "-999999px";
document.body.appendChild(textArea);
textArea.focus();
textArea.select();
return new Promise((res, rej) => {
// 執行復制命令並移除文本框
document.execCommand('copy') ? res() : rej();
textArea.remove();
});
}
}