0

I have this chrome script which works fine in my extension:

chrome.tabs.executeScript({
    code: "window.getSelection().toString();"
}, function(selection) {
    document.getElementById("output").innerHTML = selection[0];
});

But for some reason, why I try to make a function out of it, it just returns undefined.

/**
 * returns currently highlighted text
 */
function get_highlighted() {
    chrome.tabs.executeScript({
        code: "window.getSelection().toString();"
    }, function(selection) {
        return selection[0];
    });
}

// var to hold highlighted text
highlighted_text = get_highlighted();
// update HTML with highlighted text
document.getElementById("output").innerHTML = highlighted_text;

I'm having trouble debugging since no error is coming up in chrome://extensions and the console doesn't log an error.

Joe
  • 85
  • 1
  • 10
  • 1
    `get_highlighted()` does not return a value. The callback you give to the executeScript is returning a value – Taplar Jul 31 '20 at 18:20
  • Thanks! Is there a way I can make it return a value? I tried changing the inside of the function call to start with "var myVal" and then inside the callback: "myVal = selection[0]" (and then return myVal at the end of the outside function) but it didn't help – Joe Jul 31 '20 at 18:47
  • 1
    If `chrome.tabs.executeScript` is asynchronous in nature (due to the callback I would imagine it is), then it would follow similarly to https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call – Taplar Jul 31 '20 at 19:04
  • @Taplar you are the best – Joe Jul 31 '20 at 19:24

0 Answers0