Javascript 1分钟后清除剪贴板

标签 javascript clipboard

我当前正在使用以下代码将文本复制到剪贴板:

navigator.clipboard.writeText(element.value).then(function() {
    /* clipboard successfully set */
}, function() {
    /* clipboard write failed */
    console.log('Copy to clipboard failed!');
});

如果数据成功复制到剪贴板,我需要在1分钟后自动清除剪贴板。

我尝试使用 setTimeout() 方法,但从 setTimeout 调用时写入剪贴板失败。

此外,如果我使用 execCommand('copy') 方法,我会收到错误: document.execCommand(‘cut’/‘copy’) 被拒绝,因为它不是从短暂运行的用户生成的事件处理程序内部调用的。

我正在尝试让它在 Firefox 中工作。

我试图放入 setTimeout() 中的代码如下:

setTimeout(function() {
    navigator.clipboard.writeText('').then(function() {
        /* Successfully cleared clipboard */
    }, function() {
        /* Failed to clear clipboard */
    }
}, 60000);

最佳答案

Firefox 要求命令来自用户事件,例如单击。这就是为什么它在处理程序中不起作用的原因。 (您不会希望一些流氓 JavaScript 在那里粘贴数据,对吧?)

确切的措辞是命令必须调用

a short running user-generated event handler

解决方法

1 虚拟输入元素document.execCommand("copy")

使用一个虚拟输入元素,以单个空格作为值,并使用不同的 API 来选择它并将其复制到剪贴板。

function clearClipboardFromSetTimeout() {
  // This should work but does not
  //if (document.selection) document.selection.empty()
  //else window.getSelection().removeAllRanges()

  // Create a dummy input to select
  var tempElement = document.createElement("input");
  tempElement.style.cssText = "width:0!important;padding:0!important;border:0!important;margin:0!important;outline:none!important;boxShadow:none!important;";
  document.body.appendChild(tempElement);
  tempElement.value = ' ' // Empty string won't work!
  tempElement.select();
  document.execCommand("copy");
  document.body.removeChild(tempElement)
}

function doIt() {
  navigator.clipboard
    .writeText("hello")
    .then(_ =>
      navigator.clipboard.readText().then(text => console.log("before", text))
    );

  setTimeout(() => {
    clearClipboardFromSetTimeout()
    navigator.clipboard.readText().then(text => console.log("after", text));
  }, 2000);
}
<div>This will Snippet will not work in Firefox, but the <em>clearClipboardFromSetTimeout</em> method will.</div>

<button onclick='doIt()'>Set Then Clear In setTimeOut</button>

2 闪光

一个巧妙的解决方法是使用 Flash:https://brooknovak.wordpress.com/2009/07/28/accessing-the-system-clipboard-with-javascript/

3 欺骗点击处理程序

还有一些方法可以保存用户事件中的点击上下文,然后使用它来触发处理程序中的另一个点击事件,从而调用您的代码。

4 浏览器刷新

我不确定浏览器刷新是否会清除剪贴板,但如果会,您可以将状态保存到本地存储,然后强制刷新。

关于Javascript 1分钟后清除剪贴板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54953825/

相关文章:

javascript - 在 Electron 中访问剪贴板

javascript - 如何遍历json树文件并删除节点?

try block 中的 JavaScript 作用域

javascript - svg 到 json.js |我的文件去哪儿了?

clipboard - 用于保存更大剪贴板的工具

python - 应用程序退出后未设置剪贴板?

javascript - 设置变量在页面加载时不起作用,但通过控制台可以吗?

javascript - 如何将数组拆分为 m 和 n 大小的不同重复 block

clipboard - 使用 Sikuli 或 Jython 时清除 Windows 的剪贴板

android - 如何检测 "copy to clipboard"事件