Search code examples
google-chromegoogle-chrome-extensionmessage-passing

When to use message passing in chrome


I have a fairly standard use case wherein I have popup.html and background.js in a chrome extension. I need to do 2 things

  1. When the user clicks on a button in popup, let background.js know about it
  2. Send some data from background to popup

Now to implement these features I was thinking on the lines of using long-lived connections as outlined in the chrome extension docs. To that measure, this is what I have

# popup.js

var port = chrome.extension.connect({name: "LOGGERCHANNEL"});

function sendMessage(msg) {
  port.postMessage(msg);
  port.onMessage.addListener(function(msg) { 
    console.log("message recieved"+ msg); 
  });
}

sendMessage("hello world");


# background_page.js

chrome.extension.onConnect.addListener(function(port){
  console.log("Connected to Popup");
  console.assert(port.name == "LOGGERCHANNEL");


  port.onMessage.addListener(function(msg){
    console.log('Background got message:', msg);
  });
});

This works perfectly fine, however, I am at a loss on how to accomplish a sendMessage function for background.js as well. Ideally, I would like to do sendMessage('hello from bg') when a certain event occurs? How would this be possible?

Secondly, as outlined in this answer I can simply use chrome.extension.getViews() and chrome.extension.getBackgroundPage() to accomplish this task, by sharing variables.

Which is recommended approach for solving this kind of a problem?


Solution

  • I imagine you are trying to do something like - get/set options between background and popup. This is how I handled that:

    popup.js

    document.addEventListener('DOMContentLoaded', function () {
      chrome.extension.sendMessage({"msg":"getOptions"}, function(response){
        $('#clientId').val(response.options.clientId);
      });
    
      $("#setOptions" ).on("click", function(){
        chrome.extension.sendMessage({
          "msg":"saveOptions",
          "options":{ "clientId" : $('#clientId').val() }
        }); //sengMessage
      }); //on
    
    }); //addEventListener
    

    background.js

    chrome.extension.onMessage.addListener(function (request, sender, sendResponse) {
      if (request.msg == "getOptions") {
        var options = {
          clientId : localStorage.getItem('clientId') || ""
        };
        sendResponse({"msg" : "setOptions", "options" : options})
      }
    

    in some cases sendResponse will not work, i.e. when reading cookies from background page, so instead of using it you would sendMessage instead.