2022-12-20

How to Create Chrome Extension

Introduction

In this article, I will show how to create Chrome Extension.

Installing Google Chrome

Since we are developing a Chrome extension, it's necessary to have Google Chrome installed. Make sure you have the latest version of Chrome as it will have the most up-to-date features and fewer bugs. You can download it from Google's official website if you don't have it installed.

https://www.google.com/chrome/

Creating Your Extension

The creation of your Chrome extension begins with setting up a few crucial files.

Here's a general structure you might follow:

my-extension/
├── manifest.json
├── background.js
├── content.js
├── popup.js
├── popup.html
├── images/
│   ├── icon16.png
│   ├── icon48.png
│   └── icon128.png
└── css/
    └── popup.css
  • manifest.json: This is the manifest file that contains all the essential details about your extension.
  • background.js: This is your service worker script, where you put the main logic of your extension.
  • content.js: This script can read and modify the DOM of web pages that your browser visits.
  • popup.js: If your extension uses a popup, this script will define its behavior.
  • popup.html: This file structures the HTML of your popup if your extension uses one.
  • images/: This directory contains all the images used in your extension, including icons.
  • css/: This directory contains all the CSS files. In this case, popup.css would style your popup.

Manifest File Creation

The manifest file, manifest.json, is a JSON-formatted file that tells Chrome everything it needs to know about your extension. The manifest includes information like the extension's name, version, required permissions, associated files, and other important data.

Here's a simple example of manifest.json file:

manifest.json
{
  "manifest_version": 3,
  "name": "My First Chrome Extension",
  "version": "1.0",
  "description": "A simple Chrome extension.",
  "permissions": ["activeTab"],
  "action": {
    "default_popup": "popup.html",
    "default_icon": {
      "16": "images/icon16.png",
      "48": "images/icon48.png",
      "128": "images/icon128.png"
    }
  },
  "background": {
    "service_worker": "background.js"
  },
  "content_scripts": [{
    "matches": ["<all_urls>"],
    "js": ["content.js"]
  }]
}
  • manifest_version: This specifies the version of the manifest file format. For Manifest V3, this should be 3.
  • name: The name of your extension as it is displayed to users.
  • version: The version of your extension. It's a string, and it's up to you how you want to structure it, but it's recommended to follow semantic versioning (major.minor.patch).
  • description: A brief description of what your extension does.
  • permissions: The permissions that your extension requires. In this case, activeTab gives your extension temporary access to the currently active tab when the user invokes the extension - for example, by clicking its browser action.
  • action: This is a new property in Manifest V3 that replaces browser_action from Manifest V2. It contains an object that describes how the extension's icon will appear in the toolbar.
  • default_popup: The HTML file that will be shown when the user clicks on the extension's icon in the toolbar.
  • default_icon: An object that specifies different sizes of the icon to be used in different contexts.
  • background: An object that includes a service_worker field. This field points to the JavaScript file that will control the background actions of your extension.
  • content_scripts: An array of one or more objects, each representing a content script or a block of JavaScript code that Chrome will inject into the matched pages. Each object in the content_scripts list must contain:
    • matches: An array of match patterns. A match pattern is essentially a URL that begins with a permitted scheme (http, https, file, or ftp, and that can contain * characters).
    • js: An array of JavaScript files to be injected into the pages matched by the patterns defined in the matches field.

Service Worker (Background Script)

Service workers essentially act as proxy servers that sit between web applications, and the browser and the network (when available). They are intended to (amongst other things) enable the creation of effective offline experiences, and intercept network requests and take appropriate action based on whether the network is available and updated assets reside on the server. They also allow access to push notifications and background sync APIs.

Your background.js file could be as simple as:

background.js
chrome.action.onClicked.addListener((tab) => {
  chrome.scripting.executeScript({
    target: {tabId: tab.id},
    function: setPageBackgroundColor,
  });
});

function setPageBackgroundColor() {
  document.body.style.backgroundColor = 'orange';
}

In this script, when the extension icon is clicked (chrome.action.onClicked.addListener), a line of JavaScript is executed in the current tab that changes the background color of the webpage to orange. This is done through the chrome.scripting.executeScript function, which is part of the changes in Manifest V3.

Content Scripts

Content scripts are files that run in the context of web pages. By using the standard Document Object Model (DOM), they are able to read details of the web pages the browser visits, or make changes to them.

Here's a simple content.js script:

content.js
document.body.style.border = '5px solid red';

This script will add a 5px solid red border to every webpage you visit.

If your extension uses a popup (a small window that appears when users click your extension's icon), you'll define its behavior in a separate JavaScript file, often called popup.js.

In the popup script, you can listen for events like button clicks and interact with the active web page. Here's an example of a popup.js script:

popup.js
document.getElementById('myButton').addEventListener('click', async () => {
  let [tab] = await chrome.tabs.query({ active: true, currentWindow: true });

  chrome.scripting.executeScript({
    target: { tabId: tab.id },
    function: setPageBackgroundColor
  });

  function setPageBackgroundColor() {
    document.body.style.backgroundColor = 'green';
  }
});

In this script, we add an event listener to an HTML element with the id myButton. When the button is clicked, it gets the currently active tab and changes the background color of the webpage to green.

In popup.js, you can manipulate the DOM of the popup's HTML page, or use the chrome.scripting API to execute scripts in the context of the current tab.

Creating the Popup UI

Your extension's popup is the user interface that is displayed when a user clicks on the extension's icon in the Chrome toolbar. The popup UI is defined by HTML and CSS files.

Let's start by creating a popup.html file:

popup.html
<!DOCTYPE html>
<html>
  <head>
    <link rel="stylesheet" type="text/css" href="css/popup.css">
  </head>
  <body>
    <h1>Welcome to My Extension!</h1>
    <button id="myButton">Change background color</button>
    <script src="popup.js"></script>
  </body>
</html>

This HTML file starts by linking to our CSS file with a <link> tag. It then has a simple body with a title and a button. The button has an id of myButton, which we'll use in our popup.js file to add an event listener. The popup.js file is also linked in this HTML file using a <script> tag.

Next, you can define the styles for your popup in a CSS file. Here's an example of a popup.css file:

css/popup.css
body {
  font-family: "Arial", sans-serif;
  width: 200px;
  height: 200px;
  margin: 0;
  padding: 10px;
  background-color: #F0F0F0;
}

h1 {
  font-size: 1.5em;
  color: #333;
}

button {
  display: block;
  width: 100%;
  padding: 10px;
  margin-top: 20px;
  font-size: 1em;
  color: #fff;
  background-color: #007BFF;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}

button:hover {
  background-color: #0056b3;
}

In this CSS file, we've defined some basic styles for our popup's body, title, and button. The button also has a hover style to give some feedback when the user hovers over it.

Testing Chrome Extension

To test a Chrome Extension, you can follow these steps:

  1. Enable Developer Mode

    1. Open Google Chrome browser.
    2. Access the extensions page by entering chrome://extensions in the address bar.
    3. On the Extensions page, toggle the switch for Developer mode in the top-right corner to enable it.
  2. Load the Extension

    1. Click on the Load unpacked button.
    2. In the file selection dialog, navigate to the directory where your extension's code is located.
    3. Select the folder that contains your extension's manifest file (usually named manifest.json) and click Select.
  3. Test the Extension

    1. Interact with the extension's UI and features to ensure they are working as expected.

References

https://developer.chrome.com/docs/extensions/

Ryusei Kakujo

researchgatelinkedingithub

Focusing on data science for mobility

Bench Press 100kg!