Monday, May 20, 2024
65
rated 0 times [  71] [ 6]  / answers: 1 / hits: 33475  / 9 Years ago, sat, october 24, 2015, 12:00:00

Calling document.execCommand('copy'); from the Chrome developer console returns false every time.



Give it a try yourself. Open the console and run it, it never succeeds.



Any idea as to why?



enter


More From » google-chrome

 Answers
7

document.execCommand('copy') must be triggered by the user. It's not only from the console, it's anywhere that's not inside an event triggered by the user. See below, the click event will return true, but a call without event won't and a call in a dispatched event also.





console.log('no event', document.execCommand('bold'));

document.getElementById('test').addEventListener('click', function(){
console.log('user click', document.execCommand('copy'));
});

document.getElementById('test').addEventListener('fakeclick', function(){
console.log('fake click', document.execCommand('copy'));
});


var event = new Event('fakeclick')

document.getElementById('test').dispatchEvent(event) ;

<div id=test>click</ha>





See here:https://w3c.github.io/editing/execCommand.html#dfn-the-copy-command




Copy commands triggered from document.execCommand() will only affect
the contents of the real clipboard if the event is dispatched from an
event that is trusted and triggered by the user, or if the
implementation is configured to allow this. How implementations can be
configured to allow write access to the clipboard is outside the scope
of this specification.



[#64615] Thursday, October 22, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jazminuniquer

Total Points: 63
Total Questions: 121
Total Answers: 96

Location: Cambodia
Member since Thu, May 21, 2020
4 Years ago
;