Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is document.execCommand("copy") no longer working in Internet Explorer 11?

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.

like image 715
Krisztián Balla Avatar asked Mar 08 '23 07:03

Krisztián Balla


1 Answers

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>
like image 61
Krisztián Balla Avatar answered Apr 06 '23 14:04

Krisztián Balla