Build a Chrome extension from scratch with JavaScript

By

Updated

Tagged: JavaScript

Build a Chrome extension from scratch with JavaScript using Manifest V3, a popup, content script, service worker, storage, and shortcuts.

A Chrome extension is a small web app that hooks directly into the browser. You build it with the HTML, CSS, and JavaScript you already know, except your code doesn’t all live in a single page.

Instead, an extension splits its work across a few pieces:

In this tutorial we’ll build Page Notes, an extension that saves a note for whichever page you’re visiting, keyed by its URL. When you come back to that page later, your note is waiting for you. We’ll also wire up a keyboard shortcut to open the popup.

Create the project

Start by creating a new directory for the extension:

mkdir page-notes
cd page-notes

Inside it, add these files:

page-notes/
  manifest.json
  popup.html
  popup.css
  popup.js
  content.js
  service-worker.js

You don’t need a build step here. Chrome can load this directory directly.

Create the manifest

Every extension starts with manifest.json. It tells Chrome the extension’s name, which files to run, and which browser features it needs. Add this to manifest.json:

{
  "manifest_version": 3,
  "name": "Page Notes",
  "version": "1.0.0",
  "description": "Save a private note for the current page",
  "action": {
    "default_popup": "popup.html",
    "default_title": "Page Notes"
  },
  "background": {
    "service_worker": "service-worker.js"
  },
  "permissions": ["storage", "activeTab", "scripting"],
  "commands": {
    "_execute_action": {
      "suggested_key": {
        "default": "Ctrl+Shift+Y",
        "mac": "Command+Shift+Y"
      },
      "description": "Open Page Notes"
    }
  }
}

We’re using Manifest V3, the current Chrome extension format.

Look closely at the permissions array. You always want to request the smallest set of permissions your extension can get away with. Page Notes needs:

activeTab grants temporary access only after you click the extension or press its shortcut, so Chrome won’t show the broad “read and change your data on all websites” install warning.

We could have declared a static content script with matches covering every HTTP and HTTPS page, but that would give the extension permanent access to every site you visit. Since we only care about the page where you open the popup, we’ll inject the content script when you save a note.

Load the extension in Chrome

Open the extensions page in Chrome by going to this URL:

chrome://extensions

Turn on Developer mode, click Load unpacked, and pick the page-notes directory.

Once Chrome adds it to the list, pin it from the extensions menu so its icon stays in the toolbar. While you’re working on the code, come back to chrome://extensions and click the reload icon whenever you change the manifest, service worker, or content script.

Build the popup

The popup is a small HTML page. Add this to popup.html:

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width" />
    <title>Page Notes</title>
    <link rel="stylesheet" href="popup.css" />
  </head>
  <body>
    <main>
      <p id="page-title">Loading page...</p>
      <textarea
        id="note"
        rows="8"
        placeholder="Write a note about this page"
      ></textarea>
      <div class="actions">
        <span id="status" aria-live="polite"></span>
        <button id="save" type="button">Save note</button>
      </div>
    </main>
    <script type="module" src="popup.js"></script>
  </body>
</html>

Chrome blocks inline JavaScript in extension pages by default, so the code goes in a separate popup.js file. We’re loading it with type="module" because popup.js uses top-level await.

Next, add a bit of CSS for the popup:

:root {
  font-family: system-ui, sans-serif;
  color-scheme: light dark;
}

body {
  width: 340px;
  margin: 0;
}

main {
  padding: 16px;
}

#page-title {
  margin-top: 0;
  overflow: hidden;
  font-weight: 600;
  text-overflow: ellipsis;
  white-space: nowrap;
}

textarea {
  box-sizing: border-box;
  width: 100%;
  padding: 10px;
  resize: vertical;
  font: inherit;
}

.actions {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 10px;
}

#status {
  font-size: 0.85rem;
}

Click the toolbar icon and you’ll see the popup appear. It can’t do anything yet, so let’s wire up the JavaScript.

Read the current tab

First, the popup needs the current page’s URL and title. Add this to popup.js:

const titleElement = document.querySelector('#page-title')
const noteElement = document.querySelector('#note')
const saveButton = document.querySelector('#save')
const statusElement = document.querySelector('#status')

let currentUrl = ''

const [tab] = await chrome.tabs.query({
  active: true,
  currentWindow: true,
})

if (
  !tab?.url ||
  (!tab.url.startsWith('http://') && !tab.url.startsWith('https://'))
) {
  titleElement.textContent = 'This page is not available'
  noteElement.disabled = true
  saveButton.disabled = true
} else {
  currentUrl = tab.url
  titleElement.textContent = tab.title || tab.url
}

chrome.tabs.query() always returns an array because a query can match multiple tabs. Since our filter asks for the active tab in the current window, we grab the first item.

Notice we only enable the form for HTTP and HTTPS pages. Content scripts can’t run on internal pages like chrome://extensions.

Save a note with chrome.storage

Don’t use localStorage for shared extension data. Each extension context runs in its own isolated environment, whereas chrome.storage is built for extension data and works across the popup, service worker, and content scripts.

We’ll store notes in an object whose keys are URLs:

const result = await chrome.storage.local.get('notes')
const notes = result.notes || {}

noteElement.value = notes[currentUrl] || ''

saveButton.addEventListener('click', async () => {
  const latest = await chrome.storage.local.get('notes')
  const nextNotes = latest.notes || {}

  nextNotes[currentUrl] = noteElement.value.trim()

  await chrome.storage.local.set({ notes: nextNotes })

  statusElement.textContent = 'Saved'
  setTimeout(() => {
    statusElement.textContent = ''
  }, 1200)
})

Add the storage code below the tab query, running it only when currentUrl exists:

if (currentUrl) {
  const result = await chrome.storage.local.get('notes')
  const notes = result.notes || {}
  noteElement.value = notes[currentUrl] || ''
}

Keep the click listener right after it. Now save a note, close the popup, and open it again, and your note is still there.

Normalize URLs

Right now, these URLs end up with separate notes:

https://example.com/article
https://example.com/article#comments

The URL fragment usually points to a location inside the same page, so let’s strip it before using the URL as a key:

function noteKey(value) {
  const url = new URL(value)
  url.hash = ''
  return url.toString()
}

Update the assignment to use it:

currentUrl = noteKey(tab.url)

You could strip tracking parameters too, though I’d be conservative there. Query parameters often identify genuinely different pages.

Add a content script

A popup can call Chrome APIs, but it can’t modify the web page directly. For that, you need a content script, which runs inside a matching page and can read and change its DOM.

Let’s briefly highlight the page when a saved note exists. Add this to content.js:

if (!globalThis.pageNotesListenerAdded) {
  globalThis.pageNotesListenerAdded = true

  chrome.runtime.onMessage.addListener((message) => {
    if (message.type !== 'FLASH_NOTE_MARKER') {
      return
    }

    const marker = document.createElement('div')
    marker.textContent = 'You have a saved note for this page'
    marker.style.cssText = `
      position: fixed;
      z-index: 2147483647;
      right: 16px;
      bottom: 16px;
      padding: 12px 16px;
      border-radius: 6px;
      color: white;
      background: #202124;
      font: 14px system-ui, sans-serif;
    `

    document.body.append(marker)
    setTimeout(() => marker.remove(), 2200)
  })
}

The guard at the top keeps us from adding another listener every time we inject the file. Once loaded, the script waits for a message from another extension context.

Replace the status block at the end of the click listener with this code so it injects the content script and sends it a message:

let statusMessage = 'Saved'

try {
  if (tab.id !== undefined) {
    await chrome.scripting.executeScript({
      target: { tabId: tab.id },
      files: ['content.js'],
    })

    await chrome.tabs.sendMessage(tab.id, {
      type: 'FLASH_NOTE_MARKER',
    })
  }
} catch {
  statusMessage = 'Saved, but this page cannot show the marker'
}

statusElement.textContent = statusMessage
setTimeout(() => {
  statusElement.textContent = ''
}, 2200)

Reload the extension after adding the scripting permission, then open the popup on a regular website and save. You’ll see the message appear right over the page.

Chrome blocks script injection on some protected pages, including the Chrome Web Store. Your note still saves there, and the popup explains why the marker didn’t show up.

Use the service worker

Manifest V3 extensions use a service worker for background tasks. Unlike the old persistent background pages, Chrome can stop the worker whenever it has nothing to do and start it back up when an event arrives.

That means you can’t treat global variables as permanent storage. Anything that needs to survive belongs in chrome.storage.

Add this to service-worker.js:

chrome.runtime.onInstalled.addListener(async ({ reason }) => {
  if (reason !== 'install') {
    return
  }

  const result = await chrome.storage.local.get('notes')

  if (!result.notes) {
    await chrome.storage.local.set({ notes: {} })
  }
})

This initializes the storage object on first installation. We don’t strictly need it because the popup already handles a missing value, though this install listener is the right spot for one-time setup and migrations. For example, version 2 of the extension might convert an old array of notes into the URL-keyed object here.

How extension messaging works

Our extension now has three separate environments:

They talk to each other by passing messages. Use chrome.tabs.sendMessage(tabId, message) when sending to a content script in a specific tab, and chrome.runtime.sendMessage(message) to talk to other extension contexts, usually the service worker.

Give every message a type field so each listener can easily handle different message shapes:

chrome.runtime.onMessage.addListener((message, sender) => {
  if (message.type === 'NOTE_SAVED') {
    console.log('Note saved from tab', sender.tab?.id)
  }
})

If a listener needs to return an asynchronous response, return a promise where supported or use the callback pattern from the Chrome docs. Don’t assume a plain async listener behaves the same in every Chrome version.

Debug each context

The popup, page, content script, and service worker each have their own developer tools:

Most of the time, when something goes wrong, it’s one of these:

Package the extension

Before publishing, run through these checks:

  1. Add extension icons in several sizes.
  2. Confirm the extension doesn’t ask for access it no longer needs.
  3. Remove debug logs and unused permissions.
  4. Test installing it in a fresh Chrome profile.
  5. Explain every permission in the store listing.

Don’t load remotely hosted JavaScript in a Manifest V3 extension. All executable code has to live inside the extension package itself.

Create a ZIP of the files themselves with manifest.json at its root. Once you have that archive, follow how to publish a Chrome extension to the Chrome Web Store for the listing, privacy form, and review steps.

Want me to talk about your product? You can sponsor this site.

Related posts about js: