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

标签 javascript google-chrome google-chrome-extension google-chrome-app

我试图让 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/

相关文章:

javascript - 使用ajax发送$_POST变量到php

javascript - 从数组返回一个对象

javascript - 如何在 Chrome 扩展程序中检测窗口最小化/最大化事件?

javascript - Array.prototype.flat() 无法在使用 Node JS 的命令行中工作

javascript - 在网页上进行文本替换的最简洁方法? (使用 GreaseMonkey)

jquery - Google Chrome - JQuery 将选项附加到下拉菜单

google-chrome - "http://*/*"、 "https://*/*"和 "<all_urls>"在 Chrome 扩展程序的权限上下文中意味着什么

css - Chrome无法应用过滤器:hue-rotate() and transform:rotate() at the same time in an animation

google-chrome - Chrome 扩展程序 - 禁用阻止混合内容

c++ - 新手Chrome插件开发人员需要NPAPI入门方面的帮助