window.getSelection() and browser.commands.onCommand.addListener


When I try to use a hotkey detection for get a selected text, the function window.getSelection() send to me that:

Selection { anchorNode: null, anchorOffset: 0, focusNode: null, focusOffset: 0, isCollapsed: true, rangeCount: 0, caretBidiLevel: null }

Maybe it is a problem of focus ? Some add-on do the job but when I read the code, it seems it is old methods or they don’t use window.getSelection(), so is is possible to use window.getSelection() after a hotkey ? If yes, how ? if not, what is the best method with webextension.

I use the standard code of Firefox:

  "name": "Sample Commands Extension",
  "description": "Press Ctrl+Shift+U to send an event (Command+Shift+U on a Mac).",
  "manifest_version": 2,
  "version": "1.0",

  "commands": {
    "toto": {
      "suggested_key": {"default": "Ctrl+Shift+0" } ,
      "description": "Send a 'toggle-feature' event to the extension"
   "background": {
    "scripts": ["ts.js"]


 browser.commands.onCommand.addListener(function(command) {
  if (command == "toto") {
    console.log("toggling the feature!");
  var texte="";
   // var translate = require('yandex-translate')(key);
translate.translate('You can burn my house, steal my car, drink my liquor from an old fruitjar.', { to: 'ru' }, function(err, res) {

The hotkey works, but I always receive a null or nothing (I tried a lot of solution all the last day !)

I use Firefox 56 on Debian Stretch.

Thanks if you can help me :slight_smile:

1 Like

You are getting the selection from the extensions (invisible) background page, not the current website.

browser.commands.onCommand.addListener(async command => {
  const { id: tabId, } = (await browser.tabs.query({ active: true, currentWindow: true, })[0];
  const text = (await browser.tabs.executeScript(tabId, { code: 'getSelection()+""', }))[0];
  console.log('Page selection:', text);
  // ...

There’s a missing comma: from ...currentWindow: true, })[0]; to ...currentWindow: true, }))[0];.