document.execCommand(“切割” /“复制”)在书签被拒绝

问题描述 投票:5回答:1

我工作的一个书签,使当前的浏览器选项卡并将其复制到剪贴板的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(‘一刀切’/‘复制’)被拒绝,因为它不是从短期运行的用户生成的事件处理程序内调用。”在寻找Copying to clipboard with document.execCommand('copy') fails with big texts我试图生成链接的HTML功能之前解决这一问题的回答中指出。但是,下面的代码中,我得到的文本“真”,没有复制链接到剪贴板新的浏览器选项卡。

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链接的生成时间问题?或者是其他东西?

javascript firefox bookmarklet
1个回答
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>
© www.soinside.com 2019 - 2024. All rights reserved.