Chrome消息传递的范围 [英] Scope in chrome message passing
问题描述
我试图在内容脚本和后台脚本之间传递消息我想保存从后台页面发送的值,但我认为该值在消息调用的范围内停滞不前。如何在函数闭包外存储值?
I am trying to pass messages between a content script and background script I want to save the value being sent from the background page, but I think the value is stuck with in the scope of the message call. How can I store the value outside of the function closure?
Content_script.js:
var color = "red";
chrome.runtime.sendMessage({method: "getLocalStorage", key: "favColor"}, function(response) {
color = response.data;
});
Background.js:
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
if (request.method == "getLocalStorage")
sendResponse({data: localStorage[request.key]});
else
sendResponse({}); // snub them.
});
推荐答案
sendMessage
调用。要改变 color
变量,你需要将范围传递给回调函数。一种方法是使用javascript 绑定方法将外部范围传递给回调。这可能如下所示:
You are correct, the scope changes inside the callback of the sendMessage
call. To alter the color
variable you need to pass the scope into the callback. One way to do this is using the javascript bind method to pass the outer scope into the callback. This could look like:
var color = "red";
var changeColor = function(response, sender, sendResponse) {
this.color = response.data;
};
chrome.runtime.sendMessage({method: "getLocalStorage", key: "favColor"},
changeColor.bind(this));
这篇关于Chrome消息传递的范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!