简体   繁体   中英

copy to clipboard in javascript is not working

I have json data in pre tag

Below is the JS I have used

No errors in browser console. But when I paste the content in the pre tag doesn't get pasted

 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.

(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.)

Your above code fails as is (at least in Safari, Chrome, and FF, which is all I've tested), because it's initiated programmatically. But it works in those browsers if wrapped in a click event:

 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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