将变量传递给后台脚本,并在不使用存储的情况下跨选项卡在其他功能中使用它 api

Pass variable to background script and use it in other functions across tabs without using storage api

我正在将一个字符串变量从插件(从 popup.html 调用)传递到后台脚本。我正在接收字符串,但我无法在后台脚本中使用我的侦听器函数外部变量。

plugin.js:

chrome.runtime.sendMessage({'greeting': arbitraryString}, function(response) {});

background.js:

chrome.runtime.onMessage.addListener(
    function(result) {
        alert("MESSAGE RECIEVED");
        alert("arbitraryString: " + result.greeting);
        var pw = result.greeting;
}
);

alert('var saved and is: ' + pw);

直到最后一个警报为止一切正常,因为 pw 未定义。

  1. 如何在不使用存储 api 的情况下将 var 从侦听器函数传递到后台脚本内存中,以便 alert('var saved and is: ' + pw) ;成功了吗?

  2. 如果成功,pw 是否可用于注入脚本的所有选项卡?

您应该在侦听器之外声明 pw。

var pw;

chrome.runtime.onMessage.addListener(
    function(result) {
        alert("MESSAGE RECIEVED");
        alert("arbitraryString: " + result.greeting);
        pw = result.greeting;
    }
);