Getting variables outside executeScript in chrome extension

I am trying to encode a chrome extension and I have background.html with this code:

var x = "test";

function tabChanged(id, info, tab){
    if(info.status == 'complete'){
        chrome.tabs.executeScript(id, {code:"try{alert(x);}catch(e){alert(e);}"}, null);
    }
}

chrome.tabs.onUpdated.addListener(tabChanged);
chrome.tabs.getAllInWindow(null,function(tabs){
    for(var index=0; index < tabs.length; index++){
        chrome.tabs.executeScript(tabs[index].id, {code:"try{alert(x);}catch(e){alert(e);}"}, null);
    }
});

But the variable "x" is always undefined inside executeScript.

How can I get / set x from executeScript? Without the use of messaging.

+3
source share
2 answers

Content scripts are executed in the context of a web page. For more information, see Content Scripts in Chrome docs.

If you want to pass a string variable from the background page to chrome.tabs.executeScript, you should do something like this:

var x = "test";
chrome.tabs.executeScript(id, {code:"var x = '"+x+"'; try{alert(x);}catch(e){alert(e);}"},null);

, - :

var x = 1;
console.log('x=' + x);

chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
    console.log(request);
    if(request.command == 'setVar') {
        window[request.name] = request.data;
    }
});

chrome.browserAction.onClicked.addListener(function() {
    var code = "chrome.extension.sendRequest({command: 'setVar', name: 'x', data: 2});";
    chrome.tabs.executeScript(null, {code:code});
    window.setTimeout(function(){console.log('x=' + x);}, 1000);
});
+2

, undefined , , :

var yourVar = "your variable"
   //define your variable
chrome.tabs.executeScript({code: 'Your code here' + yourVar + ';}'})
   //then format it like this ({code: "Your code as a string" + your variable + "code"})

, , ,

-1

All Articles