Chrome Extension Development Examples

Practical, straight-forward examples to aid the development of chrome extensions.

Chrome Extension Development Examples

The aim of this blog post is to provide practical, straight-forward examples to aid the development of chrome extensions. This will be a live document, meaning I’ll update it frequently with meaningful examples I come across.

Table of Contents

Communicate between background script and content script

Open website after extension is installed

Communicate between background script and content script

Send a message from background script to content script

In your background script background.js:

chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
  chrome.tabs.sendMessage(
    tabs[0].id,
    { msg: "example-send-to-content-script" },
    (response) => {
      if (response) {
        console.log(response);
      }
    }
  );
});

In your content script content.js:

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request && request.msg == "example-send-to-content-script") {
    console.log("got message from background script!");
    sendResponse({ sender: "content.js", data: ":thumbsup:" });
  }
});

Send a message from content script to background script

In your content script content.js:

chrome.runtime.sendMessage({
  message: "example-send-to-background-script",
});

In your background script background.js:

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.message === "example-send-to-background-script") {
      console.log("Message from content script!");
    });
  }
});

Open website after extension is installed

In your background script background.js:

// This opens a page after extension is installed
chrome.runtime.onInstalled.addListener(function (object) {
  chrome.tabs.create({ url: "https://mikesallese.me/" }, function (tab) {
    console.log("Opening mikesallese.me after extension was installed!");
  });
});

Still need help?

Didn't find what you need? I'm happy to help folks out.

Feel free to email me at