Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
549 views
in Technique[技术] by (71.8m points)

javascript - Cannot use `document.execCommand('copy');` from developer console

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 image description here

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...