简体   繁体   English

为什么document.execCommand('copy')在控制台中有效但在代码中无效

[英]Why document.execCommand('copy') working in console but not working in code

It's not a duplicate question because I'm asking why, not how 这不是重复的问题,因为我在问为什么,而不是如何

If I paste everything between the <script></script> into the chrome console and press enter, it works perfectly, but when I load it with html, it doesn't work, why? 如果我将<script></script>之间的所有内容粘贴到chrome控制台中,然后按Enter键,则效果很好,但是当我使用html加载时,它不起作用,为什么?

<!DOCTYPE html>
<html>
<head></head>
<body></body>

<script>

  toClipboard('Hello World!');

  function toClipboard(someText) {
  //This function copies some text into your clipboard.
  //It's an ugly workaround, because there's no built-in function in JS that does this job.
    var temp = document.createElement('input');
    document.body.appendChild(temp);
    temp.value = someText;
    temp.select();
    document.execCommand('copy');
    document.body.removeChild(temp);
    console.log('"' + someText + '" should have been copied to your clipboard');
  }

</script>
</html>

Your code may not work in some browsers if you run it without user's interaction . 如果您在没有用户交互的情况下运行代码,则它们可能无法在某些浏览器中运行。

To check if execCommand was executed successfully, you can check it's return value (it would be false in OP's example): 要检查execCommand是否成功执行,可以检查它的返回值(在OP的示例中为false ):

// `execCommand` returns `false` if was not executed successfully
var res = document.execCommand('copy');

 toClipboard('Hello World!'); function toClipboard(someText) { //This function copies some text into your clipboard. //It's an ugly workaround, because there's no built-in function in JS that does this job. var temp = document.createElement('input'); document.body.appendChild(temp); temp.value = someText; temp.select(); var res = document.execCommand('copy'); document.body.removeChild(temp); console.log(res ? '"' + someText + '" should have been copied to your clipboard' : 'Copying was not successful'); } 

Solution: call toClipboard when user clicks on button : 解决方案:当用户单击按钮时,调用toClipboard

 function toClipboard(someText) { //This function copies some text into your clipboard. //It's an ugly workaround, because there's no built-in function in JS that does this job. var temp = document.createElement('input'); document.body.appendChild(temp); temp.value = someText; temp.select(); var res = document.execCommand('copy'); document.body.removeChild(temp); console.log(res ? '"' + someText + '" should have been copied to your clipboard' : 'Copying was not successful'); } 
 <button onclick="toClipboard('Hello World!');">Copy text to clipboard</button> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM