Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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

Post a Comment for "Scope In Chrome Message Passing"