Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

chrome
javascript

Advanced chrome extension development

Raj Patel

Introduction

Chrome extensions are a great way to enhance the functionality of the Chrome browser. This article is keeping the Chrome browser in mind, but the same knowledge can be used to create browser extensions for the other browsers.

If you are a beginner, go through this shot first.

We need some JavaScript for more advanced extension development to perform the logic. Mainly there are two types of scripts:

  1. Background service worker (background script before manifest v3)

  2. Content script

Background service worker

  • It runs in the context of the whole chrome browser.
  • Background script has only one instance.
  • There are certain APIs exposed by Chrome that can be utilized in this script. For example, if we want to execute some code on the installation of our extension, we can use chrome.runtime.onInstalled.addListener() . If we want to open a URL on uninstallation of the extension, we can use chrome.runtime.setUninstallURL().

Content script

  • It runs in the context of the current tab.
  • With this script, we can access and modify the page’s content using the standard Document object model - DOM.
  • We can also inject new HTML code into the current page to create overlays on the page.

Communication between these two script files

Chrome exposes a chrome.runtime.sendMessage() api to the content script and chrome.runtime.onMessage.addListener() api to the Background Service Worker.

Code

First, we create a directory and all the bare minimum files which are required for the Chrome Extension using the following commands:

$ mkdir sample-chrome-extension
$ cd sample-chrome-extension
$ touch background.js content.js    main.html     manifest.json

Let’s take a look at the content of the files that we created above:

manifest.json

{
    "name": "Hello Chrome",
    "description": "The advance extension",
    "version": "1.0",
    "manifest_version": 3,
    "background": {
        "service_worker": "background.js"
    },
    "content_scripts": [
        {
          "matches": ["http://*/*", "https://*/*"],
          "js": ["content.js"]
        }
    ],
    "action": {
      "default_popup": "main.html"
    }
  }
  • In this file, we provide the name, description, version of the extension.
  • Chrome adds new APIs or changes existing APIs Using manifest_version.
  • background.service_worker (for the background script), content_scripts.js (array for the content scripts), and action.default_popup(for the HTML file) keeps the filename (relative location to project root).
  • We can control which page script will be executed using regex using matches.
  • The HTML page default_popup shows up when we click on the extension icon.

background.js

console.log("Hi from background Script file")

chrome.runtime.onMessage.addListener( function (request, sender, sendResponse) {
    console.log("Got message from content Script: ", request);
    sendResponse('OK');
})
  • We log out a message. Then we add a listener using chrome.runtime.onMessage.addListener takes an anonymous function executed when the content script sends a message.

content.js

console.log("Hi from content script");

chrome.runtime.sendMessage({ data: document.title }, function (response) {
    console.log(response);
});
  • We log out a message.
  • We send a message using chrome.runtime.sendMessage to the background script with a payload object ({ data: document.title }) with the title of the webpage.
  • We also have an anonymous function that logs out the response.

main.html

<!DOCTYPE html>
<html>
<head>
    <title>The advance extension</title>
</head>
<body>
    <h2>
        Hi, Educative !!!
    </h2>
</body>
</html>
  • This file is a boilerplate HTML page that shows up when the extension icon is clicked with a title tag and an h2.

Installing extension

To install your extension:

  • Go to chrome://extensions/ in your Chrome.

  • Turn on Developer mode.

  • Click Load unpacked and select the newly created directory (sample-chrome-extension).

  • Click service worker. It opens the dev tool window associated with your Background Service Worker:

  • Now open a new tab and the console to see the communication logs between two scripts. Here We pass the title of the page to the background service worker:

Conclusion

In the sample code, we add two types of script files and also see how they can pass data to each other and communicate.

We can use TS instead of JS for the development of Chrome extensions.

For more information, take a look at the official docs.

RELATED TAGS

chrome
javascript
RELATED COURSES

View all Courses

Keep Exploring