在chrome扩展中获取executeScript之外的变量

Jam*_*rzs 5 javascript google-chrome global-variables google-chrome-extension

我正在尝试编写一个 chrome 扩展程序,并且我有一个包含以下代码的 background.html:

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);
    }
});
Run Code Online (Sandbox Code Playgroud)

但变量“x”在executeScript 中始终未定义。

如何从executeScript 获取/设置x?不使用消息传递。

KAd*_*dot 3

内容脚本在网页上下文中执行。有关详细信息,请参阅Chrome 文档中的内容脚本部分。

如果您想将字符串变量从后台页面传递到chrome.tabs.executeScript您必须执行以下操作:

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

如果你想修改变量,你只有一种方法 - 消息传递:

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);
});
Run Code Online (Sandbox Code Playgroud)