Build Your Own Chrome Extension: Step‑by‑Step Guide with Code Samples

This tutorial walks you through the fundamentals of Chrome extension development, covering the extension architecture, required files, manifest configuration, UI creation, background and content scripts, messaging APIs, and advanced features such as ad removal, context‑menu shortcuts, request blocking, custom new‑tab pages, and text highlighting.

JD Cloud Developers
JD Cloud Developers
JD Cloud Developers
Build Your Own Chrome Extension: Step‑by‑Step Guide with Code Samples

1. What Is a Browser Extension

Browser extensions are programs attached to the browser that extend web‑page capabilities, such as listening to browser events, modifying DOM elements, intercepting network requests, and adding context‑menu items.

2. Types of Browser Extensions

Chromium‑based extensions (e.g., Chrome)

Firefox extensions

Safari extensions

This article focuses on native development of Chrome extensions.

3. Extension Directory Structure

The typical extension folder contains the following files:

manifest.json – core configuration file (name, version, permissions, icons, etc.)

popup.html – HTML for the popup UI

popup.js – JavaScript for the popup

popup.css – CSS for the popup

background.js – background script that runs continuously and listens to browser events

content.js – script injected into web pages to interact with the DOM

4. Building a Simple Extension

1. Configure manifest

A basic manifest.json might look like this:

{
  "manifest_version": 3,
  "name": "My Sample Extension",
  "version": "1.0",
  "action": { "default_popup": "popup.html" },
  "permissions": ["tabs", "storage"],
  "background": { "service_worker": "background.js" },
  "content_scripts": [{ "matches": ["<all_urls>"], "js": ["content.js"] }]
}

2. Create the popup UI (popup.html)

Write a normal HTML page; remember to link popup.css and popup.js.

3. Popup style (popup.css)

Define the visual style of the popup.

4. Popup script (popup.js)

The script handles user interactions in the popup and sends messages to the content or background scripts. Example that listens for a click on an element with id tag:

document.getElementById('tag').addEventListener('click', function () {
  chrome.tabs.query({active: true, currentWindow: true}, function (tabs) {
    chrome.tabs.sendMessage(tabs[0].id, {greeting: 'tag'});
  });
});

5. Content script (content.js)

This script runs in the context of web pages, can listen to DOM events and receive messages.

window.addEventListener('load', function () {
  // page loaded
});
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
  console.log('Message received:', request);
  if (request.greeting === 'tag') {
    console.log('Tag clicked');
  }
});

6. Background script (background.js)

The background script runs as long as the browser is open, listening to events such as network requests. Example of blocking a specific URL:

chrome.webRequest.onBeforeRequest.addListener(
  function (details) {
    return {cancel: true};
  },
  {urls: ["*://*.example.com/*"]},
  ["blocking"]
);

5. Messaging APIs

1. Get the active tab

chrome.tabs.query({active: true, currentWindow: true}, function (tabs) {
  // tabs[0] is the active tab
});

2. Send a message to a content script

chrome.tabs.sendMessage(tabs[0].id, {greeting: "tag-remove"}, function (response) {
  console.log(response);
});

3. Send a message to another extension

chrome.runtime.sendMessage(extensionId, message, options, function (response) {
  // handle response
});

4. Listen for incoming messages

chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
  // process request
});

6. Extending the Extension’s Capabilities

1. Remove unwanted page elements (e.g., ads)

In content.js, detect elements by class or id and remove them. Example for elements with class s-p-top:

const ads = document.querySelectorAll('.s-p-top');
ads.forEach(ad => ad.remove());

2. Add a right‑click context‑menu shortcut

Define the menu in background.js and handle clicks:

chrome.contextMenus.create({
  id: 'menu2',
  title: 'Do Something',
  contexts: ['all']
});
chrome.contextMenus.onClicked.addListener(function (info, tab) {
  if (info.menuItemId === 'menu2') {
    // perform action
  }
});

3. Block requests from iframes

Use the webRequest API in the background script to cancel matching URLs, e.g., baidu.com.

4. Create a custom new‑tab page

Declare newtab in the manifest and provide newtab.html with its own CSS/JS. This page replaces the browser’s default new‑tab page.

5. Highlight selected text

Implement a feature in background.js and content.js that lets users mark important text on a page.

7. Reference Documentation

Official Chrome extension guide, Chrome API reference, and manifest permission documentation provide further details.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaScriptBrowser AutomationWeb APIs
JD Cloud Developers
Written by

JD Cloud Developers

JD Cloud Developers (Developer of JD Technology) is a JD Technology Group platform offering technical sharing and communication for AI, cloud computing, IoT and related developers. It publishes JD product technical information, industry content, and tech event news. Embrace technology and partner with developers to envision the future.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.