【问题标题】:Scope in chrome message passingchrome消息传递的范围
【发布时间】:2014-02-28 20:58:27
【问题描述】:

我正在尝试在内容脚本和后台脚本之间传递消息我想保存从后台页面发送的值,但我认为该值被卡在消息调用的范围内。如何将值存储在函数闭包之外?

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.
});

【问题讨论】:

    标签: javascript google-chrome-extension message


    【解决方案1】:

    你是对的,sendMessage 调用的回调内部的范围发生了变化。要更改 color 变量,您需要将范围传递给回调。一种方法是使用 javascript bind 方法将外部范围传递给回调。这可能看起来像:

    var color = "red";
    var changeColor = function(response, sender, sendResponse) {
      this.color = response.data;
    };
    
    chrome.runtime.sendMessage({method: "getLocalStorage", key: "favColor"}, 
        changeColor.bind(this));
    

    【讨论】:

    • this.color中的this不是指的是当前函数的作用域,而不是它之外的颜色吗。
    • 通常它会......但这就是为什么我使用bind 将“外部”范围传递给回调。你读过linked docs吗?
    猜你喜欢
    • 1970-01-01
    • 2011-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-27
    相关资源
    最近更新 更多