navigator.clipboard.writeText在http協(xié)議下不可用的坑,瀏覽器禁用了非安全域的?navigator.clipboard?對象,安全域包括本地訪問與開啟TLS安全認(rèn)證的地址,如?https?協(xié)議的地址、127.0.0.1?或?localhost?。(其實(shí)主要是http屬于非安全域)下面的方法屬于兼容了http的
function copyToClipboard(textToCopy) {
// navigator clipboard 需要https等安全上下文
if (navigator.clipboard && window.isSecureContext) {
// navigator clipboard 向剪貼板寫文本
return navigator.clipboard.writeText(textToCopy);
} else {
// 創(chuàng)建text area
let textArea = document.createElement("textarea");
textArea.value = textToCopy;
// 使text area不在viewport,同時設(shè)置不可見
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) => {
// 執(zhí)行復(fù)制命令并移除文本框
document.execCommand('copy') ? res() : rej();
textArea.remove();
});
}
}
文章來源地址http://www.zghlxwxcb.cn/news/detail-777574.html
文章來源:http://www.zghlxwxcb.cn/news/detail-777574.html
到了這里,關(guān)于關(guān)于navigator.clipboard.writeText使用遇到的坑的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!