Как скопировать текст в буфер обмена с расширением Google Chrome?

Я обнаружил, что есть экспериментальный класс буфера обмена. Но это работает только в канале разработчика, верно? Любая идея, как я могу скопировать текст?

1 ответ

В вашем скрипте контента есть это:

// 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" });

На вашей фоновой странице есть это:

// 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>
Другие вопросы по тегам