Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return value from chrome.tabs.executeScript

In popup.js i'm using the following code to display all the text within a certain div id of the current tab - and display in alert. I'm wondering how would it be possible to save the div text to a variable within 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 stored. I'm obviously going about this the wrong way. What am I doing wrong?

like image 624
user2057449 Avatar asked Feb 09 '13 16:02

user2057449


People also ask

What is executeScript ()?

executeScript() Injects a script into a target context. The script is run at document_idle by default. Note: This method is available in Manifest V3 or higher in Chrome and Firefox 101. In Safari and Firefox 102+, this method is also available in Manifest V2.


1 Answers

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, because of async nature of chrome.api

like image 182
Sudarshan Avatar answered Oct 20 '22 08:10

Sudarshan