Skip to content

Chrome extension getSelection not working

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

  }, false);
}, false);


  "manifest_version": 2,

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

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

popup.html <

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



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) => {