Writing Your First Browser Extension
Build a small Manifest V3 extension with a popup and a content script, load it for testing, debug it and prepare it for publishing.
Key takeaways
- An extension is a folder with a
manifest.jsonfile that describes its parts and the permissions it needs. - A popup shows your interface, and the
activeTabandscriptingpermissions let it work on the current page only after a click. - Load the folder as an unpacked or temporary extension to test it, then use developer tools to read errors.
- Ask for the fewest permissions possible, which protects users and makes store review simpler.
You can build a working browser extension with three or four small text files, no build tools and no server. If you know a little HTML and JavaScript, you'll finish this walkthrough with a toolbar button that counts the words on the current page, loaded and running in your own browser.
The example uses Manifest V3 and works in Chrome, Edge and other Chromium browsers. It also loads in current Firefox versions, with a few differences noted along the way.
Before you start
You need a text editor that saves plain text, a recent desktop browser and a folder you can find again. A code editor with syntax highlighting makes missing brackets obvious, but any plain text editor works. Avoid word processors, which add formatting and curly quotation marks that break code.
Decide on one small job. A good first extension does a single thing, on the page you're viewing, after you click. That scope avoids background logic, remote servers, accounts and broad permissions, which are where beginners tend to get stuck. It also gives you a finished result in an evening that you can then grow.
Use a separate browser profile for development. Your experiments can't disturb the extensions and sign-ins you rely on, and errors are easier to read in a clean browser.
Understand the parts
Extensions are made of a few kinds of pieces, and your first one needs only some of them.
A content script can see and change a page's document. The popup can't touch the page directly; it asks the browser to run code there. A background script handles events such as installation, alarms or messages. Our word counter needs the manifest, a popup and one injected function.
The finished folder looks like this:
word-count/
manifest.json
popup.html
popup.js Create the folder and manifest
Make a new folder named word-count. Inside it, create a file called manifest.json:
{
"manifest_version": 3,
"name": "Page Word Counter",
"version": "1.0.0",
"description": "Counts the words on the current page.",
"permissions": ["activeTab", "scripting"],
"action": {
"default_title": "Count words",
"default_popup": "popup.html"
}
} manifest_version, name and version are essential. The action key creates the toolbar button. activeTab grants temporary access to the tab the user is on when they click your button, and scripting lets you run code in it. Neither asks for standing access to every website.
JSON is strict: double quotes only, no comments and no trailing commas. If the browser refuses to load your folder, paste the file into a JSON formatter to find the mistake. For a refresher on the format, see JSON explained with examples.
Build the popup
Create popup.html:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<style>
body { width: 220px; font-family: system-ui, sans-serif; }
</style>
</head>
<body>
<h3>Word counter</h3>
<p id="result">Counting...</p>
<script src="popup.js"></script>
</body>
</html> The script is in a separate file on purpose. Extension pages don't allow inline JavaScript under the default content security policy, so code inside a script tag in the HTML won't run.
Add the logic
Create popup.js:
function countWords() {
const text = document.body ? document.body.innerText : "";
return text.split(/\s+/).filter(Boolean).length;
}
async function main() {
const output = document.getElementById("result");
try {
const [tab] = await chrome.tabs.query({
active: true,
currentWindow: true
});
const [injection] = await chrome.scripting.executeScript({
target: { tabId: tab.id },
func: countWords
});
output.textContent = injection.result + " words on this page";
} catch (error) {
output.textContent = "This page can't be read.";
}
}
main(); The function countWords is sent to the page and runs there, so it can read the page's document but can't use variables from the popup. The result comes back to the popup. The try block matters because browsers refuse to inject into internal pages and extension stores.
How the code fits together
Reading the script from the bottom up helps. The call to main() runs as soon as the popup opens. It asks the tabs API for the active tab in the current window. Because you clicked the toolbar button, activeTab has granted temporary access to exactly that tab.
Next, executeScript copies the function into the page and runs it. The browser returns an array of results, one for each frame it ran in; the code takes the first, which is the main page. The returned value must be something that can be serialized, such as a number, a string or a plain object. You can't hand back a live page element.
Finally, the popup writes the number into the paragraph with textContent. When the popup closes, its page is destroyed along with every variable. To remember something between openings, store it with chrome.storage and read it back at startup.
The await keyword appears because these browser calls take time and return promises. If you're new to that pattern, asynchronous JavaScript explained covers the idea.
Load it and try it
In Chrome or Edge:
- Open
chrome://extensionsoredge://extensions. - Turn on Developer mode.
- Click Load unpacked and choose your
word-countfolder. - Pin the extension from the toolbar's extensions menu.
- Visit an ordinary web page and click the button.
In Firefox, open about:debugging, choose This Firefox, click Load Temporary Add-on and select manifest.json. Temporary add-ons disappear when the browser closes.
After editing files, click the reload control on the extension's card, or in Firefox's debugging page. Popup files are re-read each time the popup opens, but manifest changes always need a reload. Compare your count with a word counter on copied text; small differences are normal because tools define a word differently.
Debug what goes wrong
Right-click inside the open popup and choose Inspect to get developer tools for it. Errors in the popup appear in that console, not the page's console. Errors from loading the manifest appear on the extensions page.
| Symptom | Likely cause |
|---|---|
| Folder won't load | Syntax error or missing file in the manifest |
| Popup stays on "Counting..." | Script path wrong or an uncaught error |
| "Page can't be read" | Internal page, store page or restricted viewer |
chrome.scripting is undefined | Missing scripting permission |
| Changes don't appear | Extension not reloaded |
Add a content script or background
If you want code to run automatically on matching pages, declare a content script in the manifest:
"content_scripts": [
{
"matches": ["https://example.com/*"],
"js": ["content.js"]
}
] Keep matches narrow. A pattern covering all URLs triggers a broad warning at install and widens what a bug can damage.
For events, Chrome uses "background": { "service_worker": "background.js" }. Firefox uses a scripts array under background for its version 3 extensions, so cross-browser projects need to account for that. A service worker stops when idle, so keep state in chrome.storage, with the storage permission. Manifest V3 background rules explain why.
Firefox also supports the browser namespace with promises, and it accepts the chrome namespace for much of the same API. Signing and some features need an extension ID declared under browser_specific_settings.
Save a setting
Suppose you want to show reading time using a speed the user can choose. Add "storage" to the permissions array, then read and write the value like this:
async function getSpeed() {
const data = await chrome.storage.local.get({ wordsPerMinute: 200 });
return data.wordsPerMinute;
}
async function saveSpeed(value) {
await chrome.storage.local.set({ wordsPerMinute: Number(value) });
} The object passed to get supplies a default for first use. Divide the word count by the saved speed and round up to get minutes. The figure of 200 here is only a starting value for the example; let people set their own. Put the input box in the popup, or on a separate options page declared with an options_ui key once the settings grow. Validate what comes back, since an empty box would otherwise save zero and break your division.
Write it safely
Even a toy extension should have good habits:
- Treat page content as untrusted. Use
textContent, neverinnerHTML, when showing it. - Don't load remote scripts, which Manifest V3 forbids anyway.
- Collect no data you don't need, and say plainly what you do collect.
- Validate messages passed between content scripts and the background.
- Keep third-party libraries few and understood.
Seeing permissions from the user's side is a useful exercise before you publish.
Publish when you're ready
Add icons in several sizes under an icons key; a favicon generator can produce small square images. Zip the folder's contents so the manifest sits at the top level of the archive, then submit it through the developer dashboard of each store: Chrome Web Store, Microsoft Edge Add-ons, Firefox Add-ons and, with Apple's developer tooling, Safari.
Registration requirements, fees and review rules vary and change, so read each store's current documentation. Expect to describe each permission, link a privacy statement if you handle data and raise the version number with every update. Protect your publishing account with strong two-factor authentication, because whoever controls it controls your users' copies.
Put the source in version control from the first day. When something breaks after a change, you'll be glad you can step back.
Ideas to extend it
Try estimating reading time from the word count, counting only the text inside an article element, adding an options page for reading speed or saving a history of counts in storage. Each teaches one new part of the platform without needing broader permissions.