Chrome Extensions: simple message passing vs chrome connection
At what point should I use a chrome connection? Is开发者_JAVA技巧 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?
(edit: documentation moved to https://developer.chrome.com/extensions/messaging )
In my personal experience with writing extensions, I tend to use sendMessage
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 sendMessage
and onMessage
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.runtime.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 sendMessage
calls.
I don't think there is anything requiring you to use them one way or another... you could use multiple sendMessage
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 sendMessage
.
As for performance... I honestly don't know, but I would expect them to at least be similar, i.e. sending 5 sendMessage
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.
To add to the other answer, using ports has an additional advantage in the form of onDisconnect
event.
Suppose a content script opens a connection to the background page. The background page will then be immediately notified of the content script being unloaded if the tab is closed or the user navigates away.
This also conceivably allows to track open tabs (with content scripts injected) without using the tabs
permission.
精彩评论