Return value from chrome.tabs.executeScript

In popup.js, I use the following code to display all text inside a specific div id of the current tab - and display in the message. I am wondering how can I save div text in a variable inside popup.js?

chrome.tabs.executeScript(null,code:"alert(document.getElementById(\"DIVid\").innerText.split(' '))"});

The above works fine, but when I try this:

var getText = chrome.tabs.executeScript(null,code:"document.getElementById(\"DIVid\").innerText.split(' ')"});

or

var getText = chrome.tabs.executeScript(null,code:"document.getElementById(\"DIVid\").innerText.split(' ')"},function(response){return response});

Nothing is saved. Obviously, I'm wrong. What am I doing wrong?

+5
source share
1 answer

Use the following code,

var getText = Array();
chrome.tabs.executeScript(tabs[tab].id, {
    "code": "document.getElementById(\"_Your_ID_Here_\").innerText.split(' ')"
}, function (result) {
    for (i = 0; i < result[0].length; i++)
    getText [i] = result[0][i];
    console.log(getText);
});

You have update variable inside callback due to chrome.api's asynchronous nature

+7
source

All Articles