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); 
else if(request.command == "getKeystroke"){
  var keystroke = db[request.id];

1 Answer 1


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) {
  • Yeah this is exactly what I ended up doing.
    – Stephen__T
    Commented Feb 23, 2012 at 15:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.