用javascript复制到剪贴板不起作用

时间:2018-09-10 14:17:50

标签: javascript html

我在pre标签中有json数据

下面是我用过的JS

浏览器控制台中没有错误。但是当我将内容粘贴到pre标签中时,就不会粘贴

var emailLink = document.querySelector('#filecontent1');
var range = document.createRange();
range.selectNode(emailLink);
window.getSelection().addRange(range);

try {
  var successful = document.execCommand('copy');
  var msg = successful ? 'successful' : 'unsuccessful';
  console.log('Copy email command was ' + msg);
} catch (err) {
  console.log('Oops, unable to copy');
}
window.getSelection().removeAllRanges();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre id="filecontent1">
        {
            "a":"string a",
            "b":"string b"
        }
    </pre>

1 个答案:

答案 0 :(得分:2)

为防止滥用,大多数浏览器仅允许您修改用户的剪贴板as part of a user-initiated event

  

document.execCommand('cut'/'copy')被拒绝,因为它不是从运行时间很短的用户生成的事件处理程序内部调用的。

(请注意,失败不会不会引发错误;浏览器仅从execCommand返回false; Firefox还会显示控制台警告消息。)

您的上述代码仍然失败(至少在Safari,Chrome和FF中,这是我测试过的),因为它是通过程序启动的。但是,如果包装在click事件中,它就可以在那些浏览器中起作用:

var testCopy = function() {
  var emailLink = document.querySelector('#filecontent1');
  var range = document.createRange();
  range.selectNode(emailLink);
  window.getSelection().addRange(range);
  try {
    var successful = document.execCommand('copy');
    var msg = successful ? 'successful' : 'unsuccessful';
    console.log('Copy email command was ' + msg);
  } catch (err) {
    console.log('Oops, unable to copy');
  }
  window.getSelection().removeAllRanges();
}

testCopy(); // this will fail, because it's not user-initiated
document.getElementById("go").onclick = testCopy; // this will work
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre id="filecontent1">
    {
        "a":"string a",
        "b":"string b"
    }
</pre>

<button id="go">Copy</button>