我试图让 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;(
最佳答案
问题的核心是异步与同步方法
在 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...
尚未完成执行,并且您得到未定义结果。您应该像在第一个代码块中一样在回调函数中编写代码。
您可能会从example获得更多灵感通过教程。
因此,在这种情况下,我认为您的问题更多是关于执行方法,而不是函数范围。希望这会有所帮助。
关于javascript - 如何使用 chrome.runtime.onMessage.addListener 参数作为全局变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48417115/