It's not a duplicate question because I'm asking why, not how
If I paste everything between the <script></script>
into the chrome console and press enter, it works perfectly, but when I load it with html, it doesn't work, why?
<!DOCTYPE html>
<html>
<head></head>
<body></body>
<script>
toClipboard('Hello World!');
function toClipboard(someText) {
//This function copies some text into your clipboard.
//It's an ugly workaround, because there's no built-in function in JS that does this job.
var temp = document.createElement('input');
document.body.appendChild(temp);
temp.value = someText;
temp.select();
document.execCommand('copy');
document.body.removeChild(temp);
console.log('"' + someText + '" should have been copied to your clipboard');
}
</script>
</html>
答案 0 :(得分:0)
如果您运行没有用户的互动,您的代码可能无法在某些浏览器中运行。
要检查execCommand
是否已成功执行,您可以检查它的返回值(在OP示例中为false
):
// `execCommand` returns `false` if was not executed successfully
var res = document.execCommand('copy');
toClipboard('Hello World!');
function toClipboard(someText) {
//This function copies some text into your clipboard.
//It's an ugly workaround, because there's no built-in function in JS that does this job.
var temp = document.createElement('input');
document.body.appendChild(temp);
temp.value = someText;
temp.select();
var res = document.execCommand('copy');
document.body.removeChild(temp);
console.log(res ? '"' + someText +
'" should have been copied to your clipboard' : 'Copying was not successful');
}
解决方案:当用户点击按钮时调用toClipboard
:
function toClipboard(someText) {
//This function copies some text into your clipboard.
//It's an ugly workaround, because there's no built-in function in JS that does this job.
var temp = document.createElement('input');
document.body.appendChild(temp);
temp.value = someText;
temp.select();
var res = document.execCommand('copy');
document.body.removeChild(temp);
console.log(res ? '"' + someText +
'" should have been copied to your clipboard' : 'Copying was not successful');
}
<button onclick="toClipboard('Hello World!');">Copy text to clipboard</button>