dev-resources.site
for different kinds of informations.
Building Chrome Extensions 101: A Quick Overview
ModsāModifications? If youāre into gaming, you know thereās nothing like playing a modded game. Itās your favorite game, but with extra power, features, and fun. Now, imagine bringing that same excitement to your web browsing experience. Thatās exactly what browser extensions doātheyāre like mods for your browser, supercharging it in ways you never thought possible.
With a Chrome extension, you can tweak your browser to suit your needs perfectlyāwhether itās blocking specific URLs, adding new features, or even giving it a completely fresh look. And the best part? You can build these extensions yourself. In this guide, Iāll take you through the step-by-step process of creating your own Chrome extension.
Getting started with web extensions is easier than you think! If you know JavaScript, itās a breezeājust a matter of learning a new API. After all, itās still JavaScript at its core.
This article is a supplement for: The Chrome Extensions Handbook: Memory-Heavy to Production-Ready
Table Of Contents
- Web Extensions 101
- Breaking Down the Manifest:
- Building a Simple Image Downloader
- The Download Function:
- Weāre Ready to Test Our Extension
- Loading the Extension
- Conclusion
Web Extensions 101
Web extensions are like mods, but for browsers. You can completely customize how the browser behavesāthink AdBlockāor how it looks, like Mozilla themes.
To get started, create a new folder!
All you need is a manifest.json
. Itās the main function but for web extensions. Itās the first file the browser looks for!
{
Ā Ā "manifest_version": 3,
Ā Ā "name": "img-downl",
Ā Ā "version": "1.0",
Ā Ā "description": "image ac?",
Ā Ā "content_scripts": [
Ā Ā Ā Ā {
Ā Ā Ā Ā Ā Ā "matches": ["<all_urls>"],
Ā Ā Ā Ā Ā Ā "js": ["content.js"]
Ā Ā Ā Ā }
Ā Ā ],
Ā Ā "permissions": [
Ā Ā Ā Ā "activeTab"
Ā Ā ]
}
The manifest contains all the metadata for your extension. Itās how browsers understand your extension and what it can do.
Breaking Down the Manifest:
-
"manifest_version": 3,
This tells the browser the API version you'll be using. With version 2 being the previous, version 3 (V3) is the latest API. Itās more secure and performant, and most browsers, including Chrome, have moved to version 3 only.
One key difference is the move from persistent background scripts to service workers. Background scripts in V2 ran during the entire lifetime of an extension (while the user is browsing), hence the āpersistentā aspect. In V3, they only run when necessary!
-
Content Scripts:
Content scripts are injected into the webpage itself. In our little extension,
content.js
will be injected into any URL that matches"matches": ["<all_urls>"]
. So, when you browse to any URL or open a new tab,content.js
will be injected into the page and run.
Content scripts, unlike background scripts, have access to the DOM.
This is the basic anatomy of a simple plugin. As you build more extension projects, youāll learn about permissions and additional functionality. For an introduction, this simple breakdown is enough.
Building a Simple Image Downloader
Ready?
This extension is inspired by a computer vision course I took a while back. We were required to implement a tool to download images from Google search.
Note: I don't suggest having this extension running at all times unless you want to download images every time you browse.
In the same folder as your manifest.json
, create content.js
and paste the following:
async function processAllImages() {
Ā Ā const images = document.querySelectorAll('img');
Ā Ā let count = 0;
Ā Ā for (const img of images) {
Ā Ā Ā Ā const url = img.src;
Ā Ā Ā Ā const filename = `image${count++}.png`; // Generate a filename for each image
Ā Ā Ā Ā try {
Ā Ā Ā Ā Ā Ā await downloadImage(url, filename);
Ā Ā Ā Ā Ā Ā console.log(`Downloaded ${filename}`);
Ā Ā Ā Ā } catch (error) {
Ā Ā Ā Ā Ā Ā console.error(`Error downloading image from ${url}:`, error);
Ā Ā Ā Ā }
Ā Ā }
}
// Run the function to process and download images
processAllImages();
Remember, a content script is injected into a webpage. For example, when you navigate to example.com
, processAllImages
will run.
All it does is grab all image elements and pass them to a download function:
const images = document.querySelectorAll('img');
The Download Function:
async function downloadImage(url, filename) {
Ā Ā return new Promise((resolve, reject) => {
Ā Ā Ā Ā fetch(url)
Ā Ā Ā Ā Ā Ā .then(response => {
Ā Ā Ā Ā Ā Ā Ā Ā if (!response.ok) throw new Error('Network response was not ok.');
Ā Ā Ā Ā Ā Ā Ā Ā return response.blob();
Ā Ā Ā Ā Ā Ā })
Ā Ā Ā Ā Ā Ā .then(blob => {
Ā Ā Ā Ā Ā Ā Ā Ā const a = document.createElement('a');
Ā Ā Ā Ā Ā Ā Ā Ā a.href = URL.createObjectURL(blob);
Ā Ā Ā Ā Ā Ā Ā Ā a.download = filename;
Ā Ā Ā Ā Ā Ā Ā Ā a.style.display = 'none';
Ā Ā Ā Ā Ā Ā Ā Ā document.body.appendChild(a);
Ā Ā Ā Ā Ā Ā Ā Ā a.click();
Ā Ā Ā Ā Ā Ā Ā Ā URL.revokeObjectURL(a.href); // Clean up the object URL
Ā Ā Ā Ā Ā Ā Ā Ā document.body.removeChild(a);
Ā Ā Ā Ā Ā Ā Ā Ā resolve();
Ā Ā Ā Ā Ā Ā })
Ā Ā Ā Ā Ā Ā .catch(error => reject(error));
Ā Ā });
}
Note: This will only work for static images. Dynamic and lazy-loaded images might be corruptedāthatās something you can handle in future iterations.
Weāre Ready to Test Our Extension
Iām using Brave, which is based on Chrome, but the process is similar across browsers.
To test, you need to enable developer mode in your chosen browser.
Loading the Extension
This extension, unchanged, should work in Mozilla as well since we donāt rely on the Chrome
namespace.
Ā Ā Ā Ā Ā Brave: Ā Ā Ā Ā
Ā Ā Ā Ā Ā Ā Ā Type brave://extensions/ in the address bar. Ā Ā Ā Ā
Ā Ā Ā Ā Ā Ā Ā Enable developer mode. Ā Ā Ā
Ā Ā Ā Ā Ā Ā Ā Load the extension by selecting the folder.
Ā Ā Ā Ā Ā Ā Ā
Ā Ā Chrome and Edge: Follow similar steps as Brave.
Ā Ā Ā Ā Ā (chrome://extensions/ or edge://extensions/)
Ā Ā Ā
Conclusion
ModsāModifications are fun! This extension might be simple, but it shows the fundamentals to get you started. Mozillaās MDN has a perfect resource to further your knowledge of web extensions (both general web extensions and browser-specific).
Remember: Turn off the extension or uninstall it when youāre done to avoid unwanted downloads.
Or better yetā¦
A Challenge: Figure out a way to receive input (hint: click, icon, and background script) and run the process images function only when the user clicks a button.
Featured ones: