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);
});