javascriptfirefox-addonfirefox-addon-sdkfirefox-addon-webextensions

browser.tabs.executeScript in Firefox Extension return value


How to return a value in browser.tabs.executeScript in Firefox Extension? I need to access var selectedText.

I have tried this but it doesn't work:

var test = browser.tabs.executeScript( {
    code: ` var selectedText = ''; if (window.getSelection) { selectedText = window.getSelection(); } else { selectedText = ''};`
  });
  
 alert(test);

Also this doesn't work:

var test = browser.tabs.executeScript( {
    code: ` window.getSelection.toString()`
  });
  
 alert(test);

Output is only [Object Promise] in alert window

alert window


Solution

  • This works now for me:

    browser.tabs.executeScript({code: "window.getSelection().toString();"}).then(result => { document.getElementById("1").value = result; });