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

问题描述:

在我们的应用程序中,我们使用以下逻辑将HTML(文本和格式)复制到剪贴板。

In our application we are using the following logic to copy HTML (text and format) to the clipboard.

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)中运行正常。

It was working fine in all major Browsers (Chrome, Firefox, Edge and Internet Explorer).

使用最新的Internet Explorer版本11.125.16299.0(更新版本:11.0.49-KB4052978)不再将HTML复制到剪贴板。

With the latest Internet Explorer version 11.125.16299.0 (Updateversion: 11.0.49 - KB4052978) the HTML is no longer copied to the clipboard.

在下面有一个安全设置:

There is a security setting for this under:

Options -> Security -> Edit level ... -> Scripting -> Allow access to clipboard

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

I changed the value from "Ask" to "Activated". This has no effect.

有人知道为什么,他们更改了什么以及其他解决方案或解决方法吗?谢谢。

Does anybody know why, what they changed and maybe another solution or workaround? Thank you.

事实证明问题并非出在 document.execCommand( copy) ,但 document.execCommand('selectAll',false,null)。虽然它可以直观地选择 div 的内容(如果不从DOM中删除它,您可以看到它的内容),但是复制命令不能识别该选择。

It turns out that the problem was not document.execCommand("copy"), but document.execCommand('selectAll',false,null). While it does visually select the content of the div (you can see it, if you don't remove it from the DOM) the selection is not recognized by the copy command.

以下代码有效:

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>