开发者

Google Chrome Extensions: Passing user highlighted webpage text to a browser_action

I'm working on a Chrome extension where I need to pass highlighted text into a browser_action. I found the following code in a Google Group, and at the time it was written it was still valid - but it doesn't work anymore..

Does anyone know an alternative solution?

background.html:

<html>
  <head>
    <script type="text/javascript">
      var selection_callbacks = [];

      function getSelection(callback) {
        selection_callbacks.push(callback);
        chrome.tabs.executeScript(null, { file: "contentscript.js" });
      };

      chrome.extension.onRequest.addListener(function (request) {
        var callback = selection_callbacks.shift();
        callback(request);
      });
    </script>
  </head>
  <body>
  </body>
</html>

popup.html:

<html>
  <head>
    <script type="text/javascript">
      function onSelection(text) {
        document.getElementById("output").innerHTML = text;
      }
      chrome.extension.getBackgroundPage().getSelection(onSelection);
    </script>
  </head>
  <body>
    <div id="output">
      This should be replaced with the selected text
    </div>
  </body>
</html>

contentscript.js:

chrome.extension.sendRequest(window.getSelection().toS开发者_StackOverflowtring());


You could use a real content script instead of injecting JavaScript into the page with chrome.extension.executeScript. You could then have background.html ask the content script for the selection using chrome.tabs.sendRequest.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜