Getting selected text in a Chrome extension

  1. Remove content.js from index.html. Content scripts are for web pages, not for extension pages such as the popup.

  2. Create index.js and load it in index.html:

      <script src="index.js"></script>
    </body>
    
  3. index.js:

    document.getElementById("save-btn").onclick = async () => {
      const [tab] = await chrome.tabs.query({active: true, currentWindow: true});
      let result;
      try {
        [{result}] = await chrome.scripting.executeScript({
          target: {tabId: tab.id},
          function: () => getSelection().toString(),
        });
      } catch (e) {
        return; // ignoring an unsupported page like chrome://extensions
      }
      document.body.append('Selection: ' + result);
    };
    
  4. edit manifest.json to allow code injection in the active tab on click:

    "permissions": ["scripting", "activeTab"]
    

Note that the popup is a separate window so it has its own separate devtools and console: right-click inside the popup and select “inspect” in the menu.

Leave a Comment