首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >document.execCommand("copy")有时会失败,但并不总是失败

document.execCommand("copy")有时会失败,但并不总是失败
EN

Stack Overflow用户
提问于 2021-04-28 15:08:29
回答 1查看 34关注 0票数 0

我有一个在双击事件处理程序上调用的函数。我在dblclick事件上调用下面的函数,将目标文本作为参数文本复制。

代码语言:javascript
复制
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");
    }

}

如果我在2秒内按确认弹出窗口的Ok,我的代码是成功的,但如果我在5-10秒后按,它就失败了。我的理解是,document.exeCommand适用于生命周期较短的用户生成事件处理程序。但我想知道什么才是真正的“短暂事件”,有没有一种方法可以让我在编程上取得成功。

EN

回答 1

Stack Overflow用户

发布于 2021-04-28 15:15:39

正如你已经提到的:

如果您在用户操作的短期事件处理程序(例如,单击处理程序)中使用这些命令,则无需任何特殊权限即可使用这些命令。(source

您遇到的问题是您使用的是confirm。此对话框中断正常流程(它会暂停操作),这会破坏您对该事件处理程序的作用域的控制。

删除该confirm应该可以解决您的问题:

代码语言:javascript
复制
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!'));
代码语言:javascript
复制
<button type="button" id="copy">Click me!</button>

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67295401

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档