Chrome extensions

Creating a browser action that toggles content scripts. 

Recently I decided to learn how to create a Chrome extension. In typical fashion, rather than go for the simplest method I decided to splunk into one of the more esoteric techniques of having code that executes within another pages context depending on interactions with the extension button itself. In other words; Clicking on the Extension button causes code to execute within the page in order to render additional UI. Which you may have seen in my WhatColor extension.

So to lets jump straight to some codes;

Firstly the script running as part of the extension, wired up in `background.js`

 var tabs = {};

// Register any pages that send us a message of type init.
chrome.extension.onConnect.addListener(function(port) {
port.onMessage.addListener(function(msg) {
if (msg.type && msg.type === 'init') {
tabs[port.sender.tab.id] = { port : port };
}
});
});

// Tell active page when the extension has been clicked.
chrome.browserAction.onClicked.addListener(function(tab) {
tabs[tab.id].port.postMessage({
type: 'click',
target: tab,
sender: tabs[tab.id].port.id
});
});

This script is responsible for listening for an ‘init’ message from any pages that wants to communicate with us (more on that in the next script). And sending a ‘click’ message to the active (listening) page when the extension’s button is clicked.

Next we have a content script wired up to be injected into a pages content.

 // Simple communication with extension pages
var port = chrome.extension.connect();

// Tell our extension that we are want to communicate.
port.postMessage({ type : 'init' });

// Start listening to messages from the extension.
port.onMessage.addListener(function(msg) {
if (!msg.type || msg.type !== 'click') {
return;
}
// TODO: React to extension click
});

This script send an ‘init’ message to the chrome extension and then listens for a ‘click’ message, that is sent when the chrome extension is clicked.

Like what you read? Give InfectiousGrin a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.