When developing chrome extension, communication between background script and content scripts is very typical use case. Chrome provides messaging APIs to achieve this goal. But this API has limitation that every message goes to the same listener.
Background script in Chrome extension usually works as a function hub for the whole extension, so background scripts usually required to process different types of messages. Then the limit of Chrome messaging API become an issue we need to face.
There are several approaches to resolve the limitation. Since API allow multiple listener, a simple and cheap solution is Responsibility Chain; adding listener for each message type, and checking message type at beginning of the listener.
This approach works, but not that graceful. And there is potential performance issue when message types increases.
So I come up a new more graceful solution: RPC Message Router
So this new RPCRouter wraps the chrome original messaging API and provides a more convenient way to invoke a remote method. To create a specific RPC Router for background page or content page is quite easy.
Using messaging API in chrome here should be careful. Coffee script will return the last executed statement result as function result, which could be potentially truthy, such as non-zero number, object. The truthy return value will make the channel become a async channel, which won’t be closed until the
sendResponse callback is invoked. But just as the handler
updateBrowserAction, the handler doesn’t need a
sendResponse callback, the issue will keep the channel alive forever. So do add
return false at the end of the method unless you can ensure the function will never yield truthy value in last statement.