从开发者控制台不能使用`document.execCommand('copy');`` [英] Cannot use `document.execCommand('copy');` from developer console
问题描述
调用
document.execCommand('copy')
必须由用户触发。它不仅来自控制台,而且不在用户触发的事件中。请参阅下文,click事件将返回true,但没有事件的调用不会发生,并且调度事件中也会发生调用。
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('false click', document.execCommand('copy'));}); var event = new Event('fakeclick')document.getElementById('test')。dispatchEvent(event);
< div id =test>点击< / ha>
$ b $ p .html#dfn-the-copy-commandrel =noreferrer> https://w3c.github.io/editing/execCommand.html#dfn-the-copy-command
从document.execCommand()触发的复制命令只会影响
真实剪贴板的内容,如果事件从
事件分派这是由用户信任和触发的,或者如果
实现被配置为允许这样做。如何将配置
的配置允许对剪贴板的写入权限在本规范的
范围外。
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?
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.
这篇关于从开发者控制台不能使用`document.execCommand('copy');``的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!