Chrome Extensions – Best Design Pattern for Asynchronous Message Passing

chromedesign-patternsjavascript

I have a background script that is responsible for getting and setting data to a localStorage database. My content scripts must communicate with the background script to send and receive data.

Right now I send a JSON object that contains the command and the data to a function. So if I'm trying to add an object to the database I'll create JSON that has a command attribute that is addObject and another object that is the data. Once this is completed the background scripts sends a response back stating that it was successful.

Another use case of the function would be to ask for data in which case it would send an object back rather than a success/fail.

The code gets kind of hacky once I start trying to retrieve the returned object from the background script.

It seems like there is probably a simple design problem to follow here that I'm not familiar with. Some people have suggested future/promise design problems but I haven't found a very good example.

Content Script

function sendCommand(cmdJson){
chrome.extension.sendRequest(cmdJson, function(response){
    //figure out what to do with response
});
}

Background script

if (request.command == "addObject"){
  db[request.id]= JSON.stringify(request.data); 
    sendResponse("success");
}
else if(request.command == "getKeystroke"){
  var keystroke = db[request.id];
  sendResponse(keystroke);
}

Best Answer

Well, I am not sure about which pattern you will call it. I would say following looks like Command pattern, I would do this..

var commands = {
         "addObject":function(request){/*Do something, send response etc*/},
         "getKeystroke":function(request){/*Do something, send response etc*/},
}

And in request handler

var requestHandler = function(request) {
      commands[request.command](request);
}
Related Topic