Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between runtime.sendMessage and port.postMessage

I am working on a Chrome extension and about to implement some message passing between my background page and the content script, it will require about 3 messages (content -> background -> content -> background) which all occur in a synchronized order.

I'm not sure what message passing API i should use for this since i don't really understand the difference between the Port API and the normal chrome.runtime API. is there something i can't do with the runtime.sendmessage that i can do with the Port.postMessage? any major differences that might make me choose one over the other?

like image 950
iddqd Avatar asked Jan 14 '16 09:01

iddqd


1 Answers

Port is a reusable, bidirectional connection.

Single messages follow the same scheme, and don't care about the state between invocations:

sendMessage -> onMessage (optionally ->) sendResponse -> callback of sendMessage

You can do most anything by that scheme.

There are maybe three aspects of Ports that make them interesting that I can think of.

  1. sendMessage is a broadcast operation.

    In case of runtime.sendMessage, it's sent to all active pages that are part of the extension. Oftentimes, only one will listen (the background page), but everyone will receive it. So if you have, say, a popup, or an options page open - everyone receives that. You could use a Port to save a tiny bit of resources, or isolate an instance of a page.

    In case of tabs.sendMessage, it will by default send to all frames within that tab. You can specify a frameId if you know it, but suppose you don't, and you're broadcasting to all frames, then determine which frame is correct - you can maintain a Port to that frame.

  2. An open Port keeps an Event Page awake. This can be useful if you're doing something asynchronous that risks unloading the Event Page. This is also a disadvantage if you don't really care about the Event Page staying awake - it prevents the improvement provided by

  3. A Port is a "death alarm": in case the context that's on the other end ceases to exist (e.g. the page with the context script was unloaded), you'll be notified by onDisconnect.

Unless you need any of the above, you can go with the simpler sendMessage-onMessage communication.

For your purposes, it would be two calls to sendMessage from the content script (as it initiates the connection) and replies from background in sendResponse. Don't forget the nuance about async responses if you need it.

like image 167
Xan Avatar answered Oct 17 '22 09:10

Xan