Search code examples
javascriptgoogle-chromegoogle-chrome-extension

Google Chrome Extension + chrome.windows.create + window.getSelection().toString()


I'm working on a chrome extension which copies the selected/highlighted text into a textarea. This is what I used so far:

chrome.tabs.executeScript( {
    code: "window.getSelection().toString();",
}, function(selection) {
    document.getElementById("output").value = selection[0];
});

But now I've switched from the popup.html to a window which I created like this

background.js:

chrome.browserAction.onClicked.addListener(function(tab) {
    chrome.windows.create({
        url: chrome.runtime.getURL("window.html"),
        type: "panel", height: 590, width:850, focused: false
        }, function(win) {
    });
});

And I can't get the selected text into this window anymore. I also copied the current URL of the activetab doing like so:

chrome.tabs.getSelected(windowId, function(tab) {
    document.getElementById('url').innerHTML = tab.url;
    var windowId = tab.id
});

and I could make this work for the new window using:

chrome.tabs.query({'active': true, 'lastFocusedWindow': true}, function (tabs) {
    document.getElementById('url').innerHTML = tabs[0].url;
});

So my question is: How can I get the selected/highlighted text into the textarea inside my newly created window? Is there something similiar to the

chrome.tabs.query() 

just for highlighted text?


Solution

  • Use executeScript's tabId parameter to inject in the clicked tab, then pass the text using any of these:

    • messaging
    • chrome.storage.local
    • encodeURIComponent in the URL: 'window.html?url=' + encodeURIComponent(text)
      then in window.js use decodeURIComponent.
    • localStorage, the classic synchronous storage shared between all internal extension pages, in case you need the result appear on the first page render without delay/flicker and don't want to pass the text in URL.

    Here's an example for localStorage.

    • background.js:

      chrome.browserAction.onClicked.addListener(function(tab) {
          getSelectedText(tab.id, function(text) {
              localStorage.selectedText = text;
              chrome.windows.create({
                  url: "/window.html",
                  type: "panel", height: 590, width:850, focused: false
              });
          });
      });
      
      function getSelectedText(tabId, cb) {
          chrome.tabs.executeScript(tabId, {
              code: "window.getSelection().toString();",
          }, function(selection) {
              cb(selection[0]);
          });
      }
      
    • window.html:

              .................
              <script src="window.js"></script>
          </body>
      </html>
      
    • window.js:

      document.getElementById('url').textContent = localStorage.selectedText || '';
      delete localStorage.selectedText;