[英]document.execCommand("copy") is failing sometimes and not always
I have a function which is invoked on double click event handler.我有一个在双击事件处理程序上调用的 function。 I call below function on dblclick event passing the target text as paremeter texttocopy.我在 dblclick 事件上调用 function 下面将目标文本作为参数 texttocopy 传递。
copyToClipboard = function (texttocopy) {
'use strict';
var answer = confirm(`Do you want to copy into the clipbaord `);
if (answer == true) {
let input = document.createElement('textarea');
input.innerHTML = texttocopy;
document.body.appendChild(input);
input.select();
let result = document.execCommand('copy', false);
document.body.removeChild(input);
if (result) return;
else alert("Failed to copy to clipboard");
}
}
If I press on Ok of the confirm popup in say 2 secs, my code is successful but if I press after 5-10 secs, its failing.如果我在 2 秒内按下确认弹出窗口的 Ok,我的代码是成功的,但如果我在 5-10 秒后按下,它会失败。 My understanding is that document.exeCommand works on short lived user generated event handlers.我的理解是 document.exeCommand 适用于短期用户生成的事件处理程序。 But I want to understand what actually counts as a "short-lived event," Is there a way I can make this successful programmatically.但我想了解什么才是真正的“短暂事件”,有没有一种方法可以通过编程方式使之成功。
As you already mentioned:正如你已经提到的:
These commands can be used without any special permission if you are using them in a short-lived event handler for a user action (for example, a click handler).如果您在用户操作的短期事件处理程序(例如,单击处理程序)中使用这些命令,则无需任何特殊权限即可使用它们。 ( source ) ( 来源)
The problem you're running into is that you're using confirm
.您遇到的问题是您正在使用confirm
。 This dialog breaks the normal flow (it halts operation), which breaks you our of that event handler's scope.此对话框会中断正常流程(它会停止操作),从而使您无法了解该事件处理程序的 scope。
Removing that confirm
should fix your problem:删除该confirm
应该可以解决您的问题:
copyToClipboard = function (texttocopy) { 'use strict'; var answer = true; //confirm(`Do you want to copy into the clipbaord `); if (answer == true) { let input = document.createElement('textarea'); input.innerHTML = texttocopy; document.body.appendChild(input); input.select(); let result = document.execCommand('copy', false); document.body.removeChild(input); if (result) return; else alert("Failed to copy to clipboard"); } } document.getElementById('copy').addEventListener('click', () => copyToClipboard( 'Copy this text to the clipboard;'));
<button type="button" id="copy">Click me!</button>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.