I am trying to code a chrome extension, and I have a 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 variable "x" is always undefined inside executeScript.
How can I get/set x from executeScript? Without using messaging.
Content scripts executes in context of web page. See Content Scripts section in Chrome docs for more information.
If you want to pass string variable from background page to chrome.tabs.executeScript
you must do something like this:
var x = "test";
chrome.tabs.executeScript(id, {code:"var x = '"+x+"'; try{alert(x);}catch(e){alert(e);}"},null);
If you want to modify variable, you have only one way - messaging:
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);
});