书签中的document.execCommand('cut'/'copy')被拒绝

时间:2019-02-09 17:29:16

标签: javascript firefox bookmarklet

我正在处理一个书签,该书签创建当前浏览器选项卡的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') fails with big texts时,我试图在函数之前生成链接的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链接是否是时间安排问题?还是其他?

1 个答案:

答案 0 :(得分:1)

您的问题与the other 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>