首页 > 解决方案 > document.execCommand('cut'/'copy') 在书签中被拒绝

问题描述

我正在开发一个小书签,它创建href当前浏览器选项卡的链接并将其复制到剪贴板。此小书签可在 Safari 中使用:

javascript:
!function(a){
var%20b=document.createElement("textarea"),
c=document.getSelection();
b.textContent=a,document.body.appendChild(b),
c.removeAllRanges(),b.select(),
document.execCommand("copy"),
c.removeAllRanges(),
document.body.removeChild(b)}
('<a%20title="'+document.title+'"%20href="'+document.location.href+'">'+document.title+'</a>');

但在 Firefox 65 中,我收到错误“document.execCommand('cut'/'copy') 被拒绝,因为它不是从短时间运行的用户生成的事件处理程序内部调用的。” 在查看Copying to clipboard with document.execCommand('copy') 失败并出现大文本时,我试图在函数之前生成链接的 html 以解决答案中指出的问题。但是,使用下面的代码,我得到了一个新的浏览器选项卡,其中包含文本“true”并且没有复制到剪贴板的链接。

javascript:
const text = ('<a%20title="'+document.title+'"%20href="'+document.location.href+'">'+document.title+'</a>');
!function(a){
var%20b=document.createElement("textarea"),
c=document.getSelection();
b.textContent=a,document.body.appendChild(b),
c.removeAllRanges(),
b.select(),
document.execCommand("copy"),
c.removeAllRanges(),
document.body.removeChild(b)}('text');

这是href链接生成的时间问题吗?或者是其他东西?

标签: javascriptfirefoxbookmarklet

解决方案


您的问题与其他 Q/A 不同:在您的情况下,您没有任何用户触发的事件。

所以不,这不是时间问题,只是你需要这样的活动。

要强制它,您可以显示一个启动屏幕,要求书签的用户单击页面。从这个点击事件你会调用execCommand('copy').

javascript:(function(a){
  var splash = document.createElement('div'),
    msg = document.createElement('span');
  splash.style='position:fixed;top:0;left:0;width:100vw;height:100vh;display:flex;justify-content:center;align-items:center;background:#FFF;z-index:999999';
  msg.textContent = 'click me';
  splash.append(msg);
  // wait for the click event
  splash.onclick = evt => {
    var b=document.createElement("textarea"),
    c=document.getSelection();
    b.textContent=a,
    document.body.appendChild(b),
    c.removeAllRanges(),
    b.select(),
    document.execCommand("copy"),
    c.removeAllRanges(),
    document.body.removeChild(b),
    document.body.removeChild(splash);
  };
  document.body.append(splash);
})

这是发生的事情的一个活生生的例子(显然不是作为书签):

(function(a){
  var splash = document.createElement('div'),
    msg = document.createElement('span');
  splash.style='position:fixed;top:0;left:0;width:100vw;height:100vh;display:flex;justify-content:center;align-items:center;background:#FFF;z-index:999999';
  msg.textContent = 'click me';
  splash.append(msg);
  // wait for the click event
  splash.onclick = evt => {
    var b=document.createElement("textarea"),
    c=document.getSelection();
    b.textContent=a,
    document.body.appendChild(b),
    c.removeAllRanges(),
    b.select(),
    document.execCommand("copy"),
    c.removeAllRanges(),
    document.body.removeChild(b),
    document.body.removeChild(splash);
  };
  document.body.append(splash);
})
('<a%20title="'+document.title+'"%20href="'+document.location.href+'">'+document.title+'</a>');
<textarea>You can paste here to check what's been copied</textarea>


推荐阅读