1

I am trying to make a simple extension, where the user can do a dictionary search by hitting a shortcut. It will open a new tab with the dictionary search of the word selected by the user. However, when I try to use "window.getSelection()", it returns an empty string. I am using the Chrome browser, latest version.

This is the background2.js file.

chrome.commands.onCommand.addListener(function(command) {
    console.log('onCommand event received for message: ', command);
    chrome.tabs.create({
        url: "https://jisho.org/search/" + encodeURIComponent(window.getSelection().toString()),
        active: true
    });
});

This is the manifest.json file.

{
   "manifest_version": 2,
   "name": "Jisho Dictionary Search",
   "permissions": [ "contextMenus" , "tabs" ],
   "version": "1.2",
   "background": {
      "scripts": [ "background.js", "background2.js" ]
   },
   "description": "Adds a shortcut to do a Jisho search automatically",
   "browser_action": {
      "default_popup" : "browser_action.html"

   },
   "commands": {

     "toggle_feature": {
         "suggested_key": { "default": "Ctrl+X" },
         "description" : "Opens new tab with word search on Jisho"
      },
      "_execute_browser_action": {
         "suggested_key": {
            "default": "Ctrl+Shift+X"
         }
      }

   }

}

Can someone help me understand why it is returning an empty string and how could I make it return the word the user selected?

  • The background script runs in a separate hidden background page. You need to run a [content script to access the web page's selection](https://stackoverflow.com/a/4532567) and pass it to the background script via messaging or executeScript's callback as shown in other answers and examples. See also [Where to read console messages from background.js in a Chrome extension?](//stackoverflow.com/a/10258029) – wOxxOm Mar 22 '19 at 16:27
  • @wOxxOm Thank you, it works now with messaging. – Pedro Lopes Mar 22 '19 at 18:06

0 Answers0