views:

45

answers:

1

At what point should I use a chrome connection? Is there ever a good reason to use both simple message passing and long lived connections? Do these two have separate performance implications?

Are there any docs other than http://code.google.com/chrome/extensions/messaging.html that compare the two approaches?

+1  A: 

In my personal experience with writing extensions, I tend to use sendRequest for state initialization, and connect for any time that I want to send things repeatedly.

As an example, my extensions usually have user-configurable options, and I need a way to send those options to my content scripts. I use sendRequest and onRequest to pass a JSON object to my content scripts. This object contains the various user-controlled settings, and possibly other state as well.

I also created a small library that allows for defining keyboard shortcuts in the background page. How it works is simple: a content script is injected into every page, which then listens for keydown and keyup events.

When an event occurs, it uses chrome.extension.connect to communicate with the background page. I think this is an excellent example of when a long-lived connection would be more useful than many sendRequests.

I don't think there is anything requiring you to use them one way or another... you could use multiple sendRequests or only send a single message with connect. I believe it's more a matter of semantics and choosing which tool makes the most sense for the job.

Also keep in mind, using connect makes it easy to store separate state for each connection, whereas it might be a tad harder to do with sendRequest.

As for performance... I honestly don't know, but I would expect them to at least be similar, i.e. sending 5 sendRequests would be roughly equivalent to sending 5 messages with connect. Keep in mind they are asynchronous, so the timing can fluctuate depending on the circumstances.

Pauan