在我们的应用程序中,我们使用以下逻辑将 HTML(文本和格式)复制到剪贴板。
function copy(element_id)
{
var aux = document.createElement("div");
aux.setAttribute("contentEditable", true);
aux.innerHTML = document.getElementById(element_id).innerHTML;
aux.setAttribute("onfocus", "document.execCommand('selectAll',false,null)");
document.body.appendChild(aux);
aux.focus();
document.execCommand("copy");
document.body.removeChild(aux);
console.log("COPY");
}
<p id="demo"><b>Bold text</b> and <u>underlined text</u>.</p>
<button onclick="copy('demo')">Copy To Clipboard Keeping Format</button>
它在所有主要浏览器(Chrome、Firefox、Edge 和 Internet Explorer)中运行良好。
使用最新的 Internet Explorer 版本 11.125.16299.0(更新版本:11.0.49 - KB4052978),不再将 HTML 复制到剪贴板。
下面有一个安全设置:
Options -> Security -> Edit level ... -> Scripting -> Allow access to clipboard
我将值从“询问”更改为“已激活”。这没有效果。
有谁知道为什么,他们改变了什么,也许还有其他解决方案或解决方法?谢谢。
最佳答案
原来问题不是document.execCommand("copy")
,而是document.execCommand('selectAll',false,null)
。虽然它确实在视觉上选择了 div
的内容(如果您不将其从 DOM 中删除,您可以看到它)复制命令无法识别该选择。
以下代码有效:
function copy(element_id)
{
var aux = document.createElement("div");
aux.setAttribute("contentEditable", true);
aux.innerHTML = document.getElementById(element_id).innerHTML;
document.body.appendChild(aux);
window.getSelection().selectAllChildren(aux);
document.execCommand("copy");
document.body.removeChild(aux);
console.log("COPY");
}
<p id="demo"><b>Bold text</b> and <u>underlined text</u>.</p>
<button onclick="copy('demo')">Copy To Clipboard Keeping Format</button>
关于javascript - 为什么 document.execCommand ("copy") 在 Internet Explorer 11 中不再有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47907503/