The Chrome extension paradigm is sandboxed. iframes and browser-tabs cannot directly communicate with each other. They must use a background script to mediate communication between them.
In a prior post, I advocate using a queue-based approach to deal with this annoyance:
https://github.com/bcoe/DoloresLabsTechTalk
Queuebert is a library designed to simplify building Chrome extensions using a queue-based approach.
- You create one instance of a server in the background.html.
- The server handles queuing up messages for the content scripts.
varserver=newQueuebert.Server();You create a client within your content scripts. The client is used to communicate between the sandboxed JavaScript environments.
- The client is used to dispatch messages to other tabs, iframes, and to the background script.
- The client has a delegate registered with it. The delegate receives messages from other clients in the system.
varclient=newQueuebert.Client({identifier: 'client',delegate: delegate});- identifier a tab with multiple iframes within it can potentially run multiple clients. The identifier is used to differentiate these clients.
- delegate the client automatically checks for inbound messages on a set interval. Messages are automatically dispatched to the delegate.
Example Delegate
vardelegate={receivedMessage: function(clientId,clientTabId,body){console.log(body.message);}};The receivedMessage message method will be executed if the following message was dispatched by another client:
client.sendMessage({action: 'receivedMessage',tabId: clientTabId,to: 'client',body: {message: 'a message'}});The clientId and clientTabId variables can be used to dispatch a message back to the originating client. The body is the body of the message dispatched by the originating client.
To keep the queue-based paradigm consistent, you can create an instance of a BackgroundClient in your background.html.
The behaviour of a background client is identical to clients in content scripts except, seeing as the background script has no tab.id, background clients have the special tab.idbackground.
Creating a BackgroundClient
varclient=newQueuebert.BackgroundClient({delegate: delegate,server: server});- delegate the delegate provided to a background client is identical to a delegate provided to other clients.
- server a BackgroundClient requires that the Server instance be provided as a dependency.
Sending a Message to a BackgroundClient
client.sendMessage({action: 'echo',tabId: 'background',to: 'background',body: {message: 'Hello World!'}});In the /example folder, there are examples of each of the concepts discussed.
The Queuebert project is a fully functional Chrome Extension. Install it, to see things in action.
Queuebert uses node.js for unit testing. run node test/index.js to execute the test suite.
Copyright (c) 2011 Attachments.me. See LICENSE.txt for further details.
