为什么 document.execCommand("copy") 在 Internet Explorer 11 中不再起作用?

Jen*_*lly 5 html javascript clipboard

在我们的应用程序中,我们使用以下逻辑将 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");
}
Run Code Online (Sandbox Code Playgroud)
<p id="demo"><b>Bold text</b> and <u>underlined text</u>.</p>
  
<button onclick="copy('demo')">Copy To Clipboard Keeping Format</button>
Run Code Online (Sandbox Code Playgroud)

它在所有主要浏览器(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
Run Code Online (Sandbox Code Playgroud)

我将值从“询问”更改为“已激活”。这没有效果。

有谁知道为什么,他们改变了什么,也许是另一种解决方案或解决方法?谢谢你。

Jen*_*lly 6

事实证明,问题不是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");
}
Run Code Online (Sandbox Code Playgroud)
<p id="demo"><b>Bold text</b> and <u>underlined text</u>.</p>
  
<button onclick="copy('demo')">Copy To Clipboard Keeping Format</button>
Run Code Online (Sandbox Code Playgroud)