简体   繁体   English

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

[英]copy to clipboard in javascript is not working

I have json data in pre tag 我在pre标签中有json数据

Below is the JS I have used 以下是我使用过的JS

No errors in browser console. 浏览器控制台中没有错误。 But when I paste the content in the pre tag doesn't get pasted 但是当我将内容粘贴到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> 

To prevent abuse, most browsers will only allow you to modify the user's clipboard as part of a user-initiated event : 为了防止滥用,大多数浏览器仅允许您在用户启动的事件中修改用户的剪贴板:

document.execCommand('cut'/'copy') was denied because it was not called from inside a short running user-generated event handler. document.execCommand('cut'/'copy')被拒绝,因为没有从运行时间很短的用户生成的事件处理程序内部调用它。

(Note that it does not throw an error on failure; the browser just returns false from the execCommand; Firefox also shows a console warning message.) (请注意,它并没有失败抛出一个错误,浏览器只是返回false从将execCommand;火狐也显示控制台警告消息。)

Your above code fails as is (at least in Safari, Chrome, and FF, which is all I've tested), because it's initiated programmatically. 您的上述代码仍然失败(至少在Safari,Chrome和FF中,这是我测试过的),因为它是通过程序启动的。 But it works in those browsers if wrapped in a click event: 但是,如果包装在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> 

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

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