javascript - 为什么 document.execCommand ("copy") 在 Internet Explorer 11 中不再有效?

标签 javascript html 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");
}
<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/

相关文章:

mfc - 拦截粘贴到(丰富的)编辑控件

javascript - 第 3 方添加到日历下拉列表未显示在子页面中

javascript - Rails 4 Javascript 图像路径

c# - 从编码行中解码特定的 HTML 标记

javascript - 警告框 - 仅在单击 (x) 时应隐藏

AppleScript : can’t set clipboard to

java - 自己的可转移不从外部应用程序返回任何 DataFlavor

javascript - 简单确认模态/弹出-MVC 5/Bootstrap 3

javascript - 使用 jQuery 单击一次元素

html - 清除 float 不工作