0

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>
  • `document.getSelection()` returns an object, not plain text. What does `alert(selObj.anchorNode.data)` print? – guest271314 Feb 08 '19 at 07:59
  • Possible duplicate of [Chrome Extension get selected text](https://stackoverflow.com/questions/19164474/chrome-extension-get-selected-text) – wOxxOm Feb 08 '19 at 08:02
  • See also [How to access the webpage DOM rather than the extension page DOM?](//stackoverflow.com/a/4532567). – wOxxOm Feb 08 '19 at 08:03
  • It prints nothing, the alert even stops showing –  Feb 08 '19 at 09:51

1 Answers1

1

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

maxpaj
  • 6,029
  • 5
  • 35
  • 56
  • ActiveTab permission might be enough since getting selection from non-active tab most likely unnecessary – Pavel Agarkov Feb 08 '19 at 09:46
  • i get an error "Uncaught TypeError: Cannot read property 'addEventListener' of null" when i try your code –  Feb 08 '19 at 09:54
  • @studentcoder Ah yes, I updated the code now. I moved the line `const test = document.querySelector("#test");` into the document eventlistener. Try that instead. – maxpaj Feb 08 '19 at 10:29
  • @PavelAgarkov yes that seems to be true. Thanks for pointing it out. – maxpaj Feb 08 '19 at 10:31