Tuesday, February 11, 2014

Month 1 - Cross-extension messaging

Success! Things are going well with my new Chrome extension!

Without going in to too many details at this point, the base extension is responsible for displaying the page. A second extension contains a number of javascript classes which build HTML elements and send them back to the main page for display. When an extension is loaded, the javascript opens a port to the base extension and sends a "register" message:

//Called on remote extension when loaded
module.Extension.prototype.register = function(){
var extension = this;
this.port = chrome.runtime.connect(module.nowExtensionId);
this.port.onMessage.addListener(function(msg){extension.handleCommand(msg);});
this.sendCommand("registerExtension", this.getDetails());
};

The base extensions listens for any incoming connections and spawns a javascript object for each new connection:

//Handles the first connection by an extension
chrome.runtime.onConnectExternal.addListener(function(port){
if (module.isBlackListed(port.sender.id))
 return;  // don't allow this extension access

port.onMessage.addListener(function(msg){
if(msg.command == "registerCard") {
module.registerCard(port,msg);
} else if(msg.command == "registerExtension"){
module.registerExtension(port,msg);
}
port.onMessage.removeListener(this);
});
});

Once the extensions are connected, we can send commands both ways. The wonderful thing is since the second extension does the registering, the base extension does not need to know any details about other extensions. Only the second extension needs to know the base extension's ID.

More details to come as I build upon this. By writing the base extension other developers should be able to write their own extensions to hook in.