How to Create a Chrome Extension Using JavaScript: A Beginner’s Guide

AJ - Sep 26 - - Dev Community

Imagine having the power to add new features or modify any website to suit your needs, directly in your browser. What if you could instantly block ads, modify the look of a page, or even integrate superhero-themed functionality? In this guide, I’ll walk you through creating your first Chrome extension using JavaScript — no superpowers required! Whether you’re a beginner or a seasoned developer, you will find that Chrome extensions are a fun way to flex your JS skills.

Image description

Here’s an outline for the article:

  1. Introduction
  2. What is Chrome Extensions?
  3. What You Will Need
  4. Setting up the Chrome Extension
  5. Creating the Manifest File
  6. Writing the Background Script
  7. Creating the Popup HTML and Popup js Script
  8. Implementing the Content Script
  9. Testing the Extension 10.Real-World Example: My First Chrome Extension
  10. Conclusion

Introduction

Are you prepared to enhance your online browsing experience? We will walk you through the process of building a Chrome extension that always opens your browser with a friendly welcome message. This course will assist you in understanding the fundamentals of developing Chrome extensions using JavaScript, regardless of your level of experience as a developer.

What is a Chrome Extension?

Let’s start with the fundamentals before digging into the code. Chrome extensions are little apps that improve your browser’s capabilities. These extensions, which are made with common web technologies like HTML, CSS, and JavaScript, let users personalize their browsing in unexpected ways.

What You Will Need:

A basic understanding of JavaScript
Google Chrome installed on your computer
A text editor (like VSCode)
Let’s dive in!

Setting up the Chrome Extension

To get started, create a new folder on your computer. This folder will hold all the files related to the Chrome extension. Let’s call it chrome-extension. Inside this folder, you will need two important files:

  1. manifest.json (the brain of your extension)
  2. background.js (the script that runs in the background).
// Here’s how to structure it:

chrome-extension/
    ├── manifest.json
    └── background.js
    └── popup.html
    └── popup.js
    └── contentScript.js

Enter fullscreen mode Exit fullscreen mode

Creating the manifest.json File

The manifest file is the heart of any Chrome extension. It defines the extension’s properties, permissions, and behavior. Let’s create a manifest.json file in our project root:

{
    "manifest_version": 3,
    "name": "Random Background Color",
    "version": "1.0",
    "description": "A Chrome extension that changes the background color of a webpage to a random color",
    "permissions": ["activeTab"],
    "action": {
      "default_popup": "popup.html"
    },
    "content_scripts": [
      {
        "matches": ["<all_urls>"],
        "js": ["contentScript.js"]
      }
    ]
  }
Enter fullscreen mode Exit fullscreen mode

If you want to know more about the manifest then you can check this Manifest Format

  1. manifest_version: 3: This specifies that we are using version 3 of the manifest. Always ensure we are using the latest version.
  2. name: The name of your extension. This will appear in the Chrome extension manager.
  3. version: This is your extension’s version. Keep this updated as you add more features.
  4. description: A short description of what your extension does.
  5. permissions: Grants permission to access and modify the currently active tab in the browser.
  6. action: Specifies the popup window (popup.html) that opens when the extension icon is clicked in the browser toolbar.
  7. content_scripts: Injects contentScript.js into every webpage visited ( allows it on all sites). The script likely changes the webpage’s background color.

Writing the background Script

The background script is responsible for handling events like opening tabs or listening for changes in browser state. Let’s create a basic background.js script.

chrome.runtime.onInstalled.addListener(() => {
  console.log("Extension installed!");
});

chrome.action.onClicked.addListener((tab) => {
  console.log("Extension icon clicked");
});

Enter fullscreen mode Exit fullscreen mode

Now breakdown the background.js

onInstalled: This event is triggered when the extension is installed or updated.
onClicked: This event is fired when the user clicks on the extension’s icon.

Creating the Popup HTML and Popup js Script

The popup is the small window that appears when the user clicks on your extension’s icon. Create a popup.html file like this:

// popup.html

<!DOCTYPE html>
<html>
  <head>
    <title>Random Background Color</title>
    <style>
      body {
        width: 200px;
        height: 100px;
        font-family: Arial, sans-serif;
        text-align: center;
      }
    </style>
  </head>
  <body>
    <h1>Random Background Color</h1>
    <button id="change-color">Change Color</button>
    <script src="popup.js"></script>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

Inpopup.js, add a script to handle the button click:

document.addEventListener("DOMContentLoaded", function () {
    const changeColorButton = document.getElementById("change-color");
    changeColorButton.addEventListener("click", function () {
      chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
        chrome.tabs.sendMessage(tabs[0].id, { action: "change-color" });
      });
    });
  });

Enter fullscreen mode Exit fullscreen mode

This script listens for the page’s DOMContentLoaded event, meaning it waits until the HTML document is fully loaded and parsed before running. Once the page is ready:

  1. It selects the button with the ID change-color.
  2. It adds a click event listener to this button.
  3. When the button is clicked, the script uses chrome.tabs.query to find the currently active tab in the browser window.
  4. After identifying the active tab, it sends a message to the content script of that tab with an action, change-color using chrome.tabs.sendMessage.

Content Script

A content script allows your extension to interact with web pages. Create a content.js file to manipulate or extract data from the web page.

function getRandomColor() {
    const letters = "0123456789ABCDEF";
    let color = "#";
    for (let i = 0; i < 6; i++) {
      color += letters[Math.floor(Math.random() * 16)];
    }
    return color;
  }

  chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
    if (request.action === "change-color") {
      const color = getRandomColor();
      document.body.style.backgroundColor = color;
     sendResponse({ status: "Background changed!" });
    }
  });
Enter fullscreen mode Exit fullscreen mode

Here’s how it works step by step:

  1. chrome.runtime.onMessage.addListener(): This is a function that listens for messages sent from other parts of the Chrome extension, such as background scripts or popup scripts.

  2. Callback Parameters:

  3. request: The message sent by another part of the extension. It contains data, like what action to perform.

  4. sender: Information about who sent the message.

  5. sendResponse: A function to send a response back to the message sender.

  6. Message Handling: Inside the callback, it checks if the request.action is change-color.

  7. Action: If the action is change-color, it changes the background color of the web page's body to random color.

  8. Response: After changing the background color, it sends a response back to the sender with the message { status: "Background changed!" }.

Testing the Extension

  1. Open Chrome and go to chrome://extensions/.
  2. Enable Developer Mode (toggle in the top right corner).
  3. Click Load Unpacked and select your extension’s folder.
  4. Your extension should now appear in the list! Click the icon in the browser toolbar to test the popup and scripts.

Add More Features

This is just the start! You can enhance your extension by adding new features like:

To learn more about storage, permissions, and options page for Chrome extensions, you can refer to the following documentation:

  1. Storage: Use chrome.storage to save user preferences. chrome.storage API
  2. Permissions: Request access to additional Chrome features (like bookmarks, and history). Permission API
  3. Options Page: Add an options page to allow users to configure the extension. Options Page
  4. For more details, visit the Chrome Extensions documentation.

Real-World Example: My First Chrome Extension

When I created my first Chrome extension, I was eager to make my browsing experience more personalized. The idea of a browser welcoming me whenever I opened it felt like adding a touch of personality to my digital routine. It was the simplest idea, but the satisfaction of seeing it work was huge. For developers just getting started, these small wins are what keep us pushing forward.

Conclusion: Make It Yours.

Chrome extensions are powerful tools that can enhance your browser experience. This tutorial is just the beginning — once you’re comfortable with the basics, you can extend this project further by adding custom buttons, integrating APIs, or even storing user preferences.


. . . . .
Terabox Video Player