Chrome extension getSelection not working

Tags: ,



I am trying to create a chrome extension which only consist of a button. When this button is clicked, it should make an alert box which contains the highlighted textarea on a page. I can’t get it to work. I can make it alert a hardcoded string, but not make it alert some highlighted text / selected textarea on a page.

Here is the javascript code popup.js:

document.addEventListener('DOMContentLoaded', function() {
test.addEventListener('click', function() {

    var selObj = document.getSelection(); 
    alert(selObj);

  }, false);
}, false);

manifest.json

    {
  "manifest_version": 2,

  "name": "test ",
  "description": "test",
  "version": "1.0",

  "browser_action": {
   "default_icon": "icon.png",
   "default_popup": "popup.html"
  },
  "permissions": [
   "activeTab"
   ]
}

popup.html <

!doctype html>
<html>
  <head>
    <title>Test</title>
    <script src="popup.js"></script>
  </head>
  <body>
    <h1>Test</h1>
    <button id="test">Test</button>
  </body>
</html>

Answer

You could fetch the selection by loading a script into the page using the executeScript method in the Tabs API. You may have to add the tabs permission to your manifest.json.

To execute the script you first need to fetch the tab ID, you can do that using query and querying on fetching the active tab in the current window.

document.addEventListener('DOMContentLoaded', function() {
    const test = document.querySelector('#test');
    test.addEventListener('click', function() {
        chrome.tabs.query({ currentWindow: true, active: true }, (tabs) => {
            chrome.tabs.executeScript(tabs[0].id, { code: `document.getSelection().toString()` }, (result) => {
                alert(result);
            });
        });
    });
});



Source: stackoverflow