如何使用 chrome.runtime.onMessage.addListener 参数作为全局变量?

How to use chrome.runtime.onMessage.addListener parameter as global variable?

我正在尝试使 chrome.runtime.onMessage.addListener 参数失效。但它只在方法内部起作用。

chrome.runtime.onMessage.addListener(function(response, sender, sendResponse){
        alert(response); // its ok!
});

但是当我试图将其声明为外部变量时,它不起作用。

chrome.runtime.onMessage.addListener(function(response, sender, sendResponse){
        response = response;
});

alert(response); // Underfined;(

问题的核心是异步vs同步方法

chrome-extension tutorial中有:

Most methods in the chrome.* APIs are asynchronous: they return immediately, without waiting for the operation to finish. If you need to know the outcome of that operation, then you pass a callback function into the method. That callback is executed later (potentially much later), sometime after the method returns.

关于这个问题,如果你这样写代码:

chrome.runtime.onMessage.addListener(function(response, sender, sendResponse){
        response = response;
});

alert(response);

chrome.runtime...alert(...)会同时执行,alert函数无法获取参数response,因为chrome.runtime...没有' 完成执行,你会得到 undefined 结果。您应该像在第一个代码块中那样在回调函数中编写代码。

您可能会从example教程中获得更多灵感。

所以在这种情况下,我认为你的问题更多的是 执行方法 而不是 函数范围 。希望这会有所帮助。