Why is document.execCommand(“copy”) no longer work

2019-07-20 21:48发布

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>

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

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.

1条回答
不美不萌又怎样
2楼-- · 2019-07-20 22:40

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.

The following code works:

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>

查看更多
登录 后发表回答