代码之家  ›  专栏  ›  技术社区  ›  Mark Allison

如何在chrome扩展中使用链接复制到剪贴板?

  •  0
  • Mark Allison  · 技术社区  · 7 年前

    我最近第一次创建了一个chrome扩展。我的页面上有一个copy按钮,当扩展加载为web页面时,它可以正常工作。但是,当我将其作为扩展加载时,copy函数不起作用。

    我的 manifest.json 权限如下:

    "permissions": [
      "webNavigation",
      "storage",
      "clipboardWrite",
      "clipboardRead"
    ]
    

    我的代码 popout.html 要复制的页如下所示:

            <div id="legacyCopyLabel">
                <a onclick="copyText(getElementById('legacy'))" class="alignright">COPY</a>
            </div>
    

    以及 copyText()

    function copyText(element) {
        var range, selection, worked;
    
        if (document.body.createTextRange) {
          range = document.body.createTextRange();
          range.moveToElementText(element);
          range.select();
        } else if (window.getSelection) {
          selection = window.getSelection();        
          range = document.createRange();
          range.selectNodeContents(element);
          selection.removeAllRanges();
          selection.addRange(range);
        }
    
        try {
          document.execCommand('copy');
          updateStatus ('Copied address', 'info');
        }
        catch (err) {
          alert('Unable to copy the address');
        }
      }
    

    如果您想查看,这里有完整的代码: https://github.com/markallisongit/handcash-chrome

    Chrome分机位于Chrome商店: https://chrome.google.com/webstore/detail/handcash-handle-converter/bnkohbkbipagdhplhkhgonbalbjigpoh

    1 回复  |  直到 7 年前
        1
  •  2
  •   Denis L    7 年前

    <a onclick="..."> .

    解决方案是将您的代码放入一个单独的 .js