如何从Google Chrome扩展程序将文字复制到剪贴板?

tha*_*era 4 clipboard google-chrome

我发现有一个实验性的剪贴板类.但它只适用于开发频道,对吗?知道如何复制文本吗?

Ath*_*ena 6

在您的内容脚本中,请:

// step 1: get the text you mean to copy
// (actual implementation not included)

// step 2: send it to your background page
chrome.extension.sendRequest({ text: "text you want to copy" });
Run Code Online (Sandbox Code Playgroud)

在您的背景页面中,有这样的:

// step 3: set up your background page HTML
// and 
<html>
 <head>
 <script type="text/javascript">
   chrome.extension.onRequest.addListener(function (msg, sender, sendResponse) {

      var textarea = document.getElementById("tmp-clipboard");

      // now we put the message in the textarea
      textarea.value = msg.text;

      // and copy the text from the textarea
      textarea.select();
      document.execCommand("copy", false, null);


      // finally, cleanup / close the connection
      sendResponse({});
    });
  </script>
  </head>

  <body>
    <textarea id="tmp-clipboard"></textarea>
  </body>
</html>
Run Code Online (Sandbox Code Playgroud)