Daniel
Daniel

Reputation: 1198

Behavior of extension.onConnect, extension.connect and Port

I am curious how onConnect, connect, and port.postMessage/onMessage are supposed to behave if there are multiple listeners. The documentation is unclear what happens, and where disconnect comes in.

Say I have three contexts (background page, content script, and a browser action popup) - each on startup has registered an onConnect listener. The background page wants to send a message to both of them - can I simply connect(), then send a message via the Port? What if I want receipt confirmation? Can I say - port.postMessage({ received: true }) in both of the contexts that received the onConnect? Will I receive two messages in the guy who connect()ed? Will I receive an onConnect() message in the background page where I called the connect()?

I've read http://code.google.com/chrome/extensions/messaging.html and http://code.google.com/chrome/extensions/extension.html# - they make it pretty clear how sendRequest and onRequest work, but I need delivery confirmation, which I don't think I can adequately get out of sendRequest.

My question boils down to: how many "ends" can there be for a Port object, and how does it handle "disconnect" calls from any of the ends?

Upvotes: 1

Views: 275

Answers (1)

jjNford
jjNford

Reputation: 5270

The ports are actually pretty simple. I think an example will work better, mind you I'm not using a content script, but here is a utility script I build called socket.js that allows continuous 2 way communication between a popup and background page.

https://github.com/jjNford/chrome-extension-socket

I am currently using it in this extension:

https://chrome.google.com/webstore/detail/jgekomkdphbcbfpnfjgcmjnnhfikinmn

The postTask API is nice for UX purposes. I know I didn't directly answer your question but I hope this helps you.

Upvotes: 1

Related Questions