Chrome extension is one of the most effective ways to personalize the user experience on your website. You can use a Chrome extension to connect users with your brand, establish trust and credibility, and even gather more data about how they are using your site.
In this article we’ll break down the steps of how to make a Chrome extension for your website. By following these guidelines, you will have a custom extension that is tailored to your website’s needs.
Table of Contents
How To Make Chrome Extension For Website
Extensions are made of different, but cohesive, components. Components can include background scripts, content scripts, an options page, UI elements and various logic files. Extension components are created with web development technologies: HTML, CSS, and JavaScript. An extension’s components will depend on its functionality and may not require every option.
This tutorial will build an extension that allows the user to change the background color of the currently focused page. It will use many of the extension platform’s components to give an introductory demonstration of their relationships.
To start, create a new directory to hold the extension’s files.
The completed extension can be downloaded here.
#Create the manifest
Extensions start with their manifest. Create a file called manifest.json and include the following code.
{
"name": "Getting Started Example",
"description": "Build an Extension!",
"version": "1.0",
"manifest_version": 3
}#Load an unpacked extension
The directory holding the manifest file can be added as an extension in developer mode in its current state. To load an unpacked extension in developer mode, follow these steps:
- Open the Extension Management page by navigating to
chrome://extensions.- Alternatively, open this page by clicking on the Extensions menu button and selecting Manage Extensions at the bottom of the menu.
- Alternatively, open this page by clicking on the Chrome menu, hovering over More Tools then selecting Extensions
- Enable Developer Mode by clicking the toggle switch next to Developer mode.
- Click the Load unpacked button and select the extension directory.
Ta-da! The extension has been successfully installed. Because no icons were included in the manifest, a generic icon will be created for the extension.
#Add functionality
The extension is now installed, but it doesn’t currently do anything because we haven’t told it what to do or when to do it. Let’s fix that by adding some code to store a background color value.
#Register the background script in the manifest
Background scripts, like many other important components, must be registered in the manifest. Registering a background script in the manifest tells the extension which file to reference, and how that file should behave.
{
"name": "Getting Started Example",
"description": "Build an Extension!",
"version": "1.0",
"manifest_version": 3,
"background": {
"service_worker": "background.js"
}
}Chrome is now aware that the extension includes a service worker. When you reload the extension, Chrome will scan the specified file for additional instructions, such as important events it needs to listen for.
#Create the background script
This extension will need information from a persistent variable as soon as it’s installed. Start by including a listening event for runtime.onInstalled in the background script. Inside the onInstalled listener, the extension will set a value using the storage API. This will allow multiple extension components to access that value and update it. Inside the extension’s directory create a file named background.js and add the following code.
// background.js
let color = '#3aa757';
chrome.runtime.onInstalled.addListener(() => {
chrome.storage.sync.set({ color });
console.log('Default background color set to %cgreen', `color: ${color}`);
});#Add the storage permission
Most APIs, including the storage API, must be registered under the "permissions" field in the manifest for the extension to use them.
{
"name": "Getting Started Example",
"description": "Build an Extension!",
"version": "1.0",
"manifest_version": 3,
"background": {
"service_worker": "background.js"
},
"permissions": ["storage"]
}#Inspect the background script
Navigate back to the extension management page and click the Reload link. A new field, Inspect views, becomes available with a blue link, service worker.
Click the link to view the background script’s console log, “Default background color set to green“
#Introduce a user interface
Extensions can have many forms of a user interface; this one will use a popup. Create and add a file named popup.html to the extension’s directory. This extension uses a button to change the background color.
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="button.css">
</head>
<body>
<button id="changeColor"></button>
</body>
</html>Like the background script, this file must be declared in the manifest in order for Chrome to present it in the extension’s popup. To do this, add an action object to the manifest and set popup.html as the action’s default_popup.
{
"name": "Getting Started Example",
"description": "Build an Extension!",
"version": "1.0",
"manifest_version": 3,
"background": {
"service_worker": "background.js"
},
"permissions": ["storage"],
"action": {
"default_popup": "popup.html"
}
}This popup’s HTML references an external CSS file named button.css. Add another file to the extension’s directory, name it appropriately, and add the following code.
button {
height: 30px;
width: 30px;
outline: none;
margin: 10px;
border: none;
border-radius: 2px;
}
button.current {
box-shadow: 0 0 0 2px white,
0 0 0 4px black;
}Designation for toolbar icons is also included under action in the default_icon field. Download the images folder here, unzip it, and place it in the extension’s directory. Update the manifest so the extension knows how to use the images.
{
"name": "Getting Started Example",
"description": "Build an Extension!",
"version": "1.0",
"manifest_version": 3,
"background": {
"service_worker": "background.js"
},
"permissions": ["storage"],
"action": {
"default_popup": "popup.html",
"default_icon": {
"16": "/images/get_started16.png",
"32": "/images/get_started32.png",
"48": "/images/get_started48.png",
"128": "/images/get_started128.png"
}
}
}Extensions also display images on the extension management page, the permissions warning, and favicon. These images are designated in the manifest under icons.
{
"name": "Getting Started Example",
"description": "Build an Extension!",
"version": "1.0",
"manifest_version": 3,
"background": {
"service_worker": "background.js"
},
"permissions": ["storage"],
"action": {
"default_popup": "popup.html",
"default_icon": {
"16": "/images/get_started16.png",
"32": "/images/get_started32.png",
"48": "/images/get_started48.png",
"128": "/images/get_started128.png"
}
},
"icons": {
"16": "/images/get_started16.png",
"32": "/images/get_started32.png",
"48": "/images/get_started48.png",
"128": "/images/get_started128.png"
}
}By default, extensions appear in the extensions menu (the puzzle piece). Pinning the extension will display the icon in the toolbar.
If the extension is reloaded at this stage, it will include the provided icon rather than the default placeholder, and clicking the action will open a popup that displays a button showing the default color.
The last step for the popup UI is adding color to the button. Create and add a file named popup.js with the following code to the extension’s directory.
// Initialize button with user's preferred color
let changeColor = document.getElementById("changeColor");
chrome.storage.sync.get("color", ({ color }) => {
changeColor.style.backgroundColor = color;
});This code grabs the button from popup.html and requests the color value from storage. It then applies the color as the background of the button. Include a script tag to popup.js in popup.html.
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="button.css">
</head>
<body>
<button id="changeColor"></button>
<script src="popup.js"></script>
</body>
</html>Reload the extension to view the green button.
#Layer logic
The extension now has a custom icon and a popup, and it colors the popup button based on a value saved to the extension’s storage. Next, it needs logic for further user interaction. Update popup.js by adding the following to the end of the file.
// When the button is clicked, inject setPageBackgroundColor into current page
changeColor.addEventListener("click", async () => {
let [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
chrome.scripting.executeScript({
target: { tabId: tab.id },
function: setPageBackgroundColor,
});
});
// The body of this function will be executed as a content script inside the
// current page
function setPageBackgroundColor() {
chrome.storage.sync.get("color", ({ color }) => {
document.body.style.backgroundColor = color;
});
}The updated code adds a click event listener to the button, which triggers a programmatically injected content script. This turns the background color of the page the same color as the button. Using programmatic injection allows for user-invoked content scripts, instead of auto inserting unwanted code into web pages.
The manifest will need the activeTab permission to allow the extension temporary access to the current page, and the scripting permission to use the Scripting API’s executeScript method.
{
"name": "Getting Started Example",
...
"permissions": ["storage", "activeTab", "scripting"],
...
}The extension is now fully functional! Reload the extension, refresh this page, open the popup and click the button to turn it green! However, some users may want to change the background to a different color.Gotchas
Extensions can not inject content scripts on internal Chrome pages like “chrome://extensions”. Be sure to try out the extension on a real webpage like https://google.com.
#Give users options
The extension currently only allows users to change the background to green. Including an options page gives users more control over the extension’s functionality, further customizing their browsing experience.
Start by creating a file in the directory named options.html and include the following code.
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="button.css">
</head>
<body>
<div id="buttonDiv">
</div>
<div>
<p>Choose a different background color!</p>
</div>
</body>
<script src="options.js"></script>
</html>Then register the options page in the manifest,
{
"name": "Getting Started Example",
...
"options_page": "options.html"
}Reload the extension and right-click the extension icon in the toolbar then select Options. Alternatively, click DETAILS and scroll down the details page and select Extension options.
The last step is to add the options logic. Create a file named options.js in the extension’s directory with the following code.
let page = document.getElementById("buttonDiv");
let selectedClassName = "current";
const presetButtonColors = ["#3aa757", "#e8453c", "#f9bb2d", "#4688f1"];
// Reacts to a button click by marking the selected button and saving
// the selection
function handleButtonClick(event) {
// Remove styling from the previously selected color
let current = event.target.parentElement.querySelector(
`.${selectedClassName}`
);
if (current && current !== event.target) {
current.classList.remove(selectedClassName);
}
// Mark the button as selected
let color = event.target.dataset.color;
event.target.classList.add(selectedClassName);
chrome.storage.sync.set({ color });
}
// Add a button to the page for each supplied color
function constructOptions(buttonColors) {
chrome.storage.sync.get("color", (data) => {
let currentColor = data.color;
// For each color we were provided…
for (let buttonColor of buttonColors) {
// …create a button with that color…
let button = document.createElement("button");
button.dataset.color = buttonColor;
button.style.backgroundColor = buttonColor;
// …mark the currently selected color…
if (buttonColor === currentColor) {
button.classList.add(selectedClassName);
}
// …and register a listener for when that button is clicked
button.addEventListener("click", handleButtonClick);
page.appendChild(button);
}
});
}
// Initialize the page by constructing the color options
constructOptions(presetButtonColors);Four color options are provided then generated as buttons on the options page with onclick event listeners. When the user clicks a button, it updates the color value in the extension’s storage. Since all of the extension’s files pull the color information from this storage, no other values need to be updated.
chrome extension project ideas
Internet is overflowing with information on anything you need. But when you go online you stand on a thin ridge with task at hand on one side and time chewing activities on the other. And somehow the gravity is more powerful over on the other side. It’s easy to get pulled into aimless scrolling on facebook or twitter or watching cat videos, they never get old, do they? And quite often I found myself doing the same, I somehow needed to put a check on how I spent my time online.
Recently I signed up for the DevIdeas newsletter, with all the time wastage control thing in my head I receive their second newsletter on a Saturday evening. One of the ideas in that newsletter is shown below.

Something like this would have totally worked for me. If I could find out the exact amount of time that I waste online, then maybe I will be able to control my habits. But in my knowledge nothing like this existed yet, and so, I decided to work on the idea.
Beginning
The original idea suggests to show amount of time spent on certain sites on that day, month and the year. Though it sounds nice, in my opinion it holds more of a cosmetic value than working towards helping us in achieving the goal. I decided to deviate away a little from the path the idea follows, and show the time collectively spent on twitter, facebook and google plus on just that day.
A while ago I read this book called The Shape of design, one of the brilliant advice from the book that stuck with me and have always found its usefulness is when you venture on a project, initially, think of the worst possible way to tackle it. The idea being that each iteration after the initial step will definitely be an improvement over the previous, because there is no conceivable way you can come up with anything worst. In my case it was to display time spent on certain websites.
Exploring
From the very beginning I knew I wanted the background to be white. No decorations, mountains and bold colors. I have used several of other new-tab extensions, and they end up adding huge amount of visual weight to a simple new-tab page. This kills the very simplistic approach chrome follows.


After going through a couple of design iterations (some of them shown above) I settled with the one below, it seemed simple and direct.

Though I had to struggle a bit with Chrome API, development part of this version was relatively simple. I got it working in about an hour. As soon as it was done I sent it out to Arjun, the awesome guy behind the Dev Ideas newsletter for his thoughts on it. And he has been kind enough to provide his invaluable feedbacks and suggestions throughout the project. One of which was to allow people to add the sites that they’d like to be tracked. It seemed like a logical thing to do, if I was to ever ship it I can’t expect people to be wasting their time online just on social networking sites. Moreover there are other websites that I think can save quiet a lot of time by not visiting them as often.
Adding and editing choices
On installation would be the perfect time to ask for the sites people wished to be tracked. Following are the design iteration that this part of the project went through. Leftmost being the final one. The settings panel pops in from the left in a “sidebaresque” fashion to allow editing of choices.



For the extension to work the provided input are only supposed to be the domain names of the websites. To get this message through to the user, I left the first few fields pre filled and amazingly enough, that did the job. The extension at that moment also allowed editing of choices, which I found myself misusing. Call me weak, but each time the timer crossed my self decided limit for that day, I would simply get rid of the website from the list. I had to come up with a way of locking the choices to avoid such business.
Limiting and Locking

I was using the extension daily as I was building it. Along the process it went through a couple of additions and changes, like adding of quotes for “motivation”, new icons and one more key feature which we will be discussing later. Since we are on with choices let us be done with that first. As apparent from the images above I decided to limit the number of choices that the user will be allowed to enter to five. As limiting the number of choices leads to careful picking rather than impetuous filling.
How and when to allow users to lock their choices was one of the difficult part of the whole design process. You can read my question here on ux.stackexchange.com which explains the situation better. It received some interesting answers but none I found satisfactory . Finally I decided to leave it up to the user as to when they felt it was necessary to lock the choices they have selected.

Adding the graph
The most important and final feature added to the extension was the activity graph. The activity graph provided a visual history of time wasted online, each day added a new bar to the graph. The more time you waste, the taller the bar for that day would be. Its easier to improve when you can see right in front of your eyes how you’ve been doing. The idea was simple, on the very first day you browse the web as you normally would. This added the very first bar in the graph. Which acts as a benchmark, a limit you’re not supposed to cross. With each passing day you try to keep the bar for that day shorter than one from the day before.

I have been using the final version for almost 7 days now and managed to cut about 10 minutes off of my daily time wastage.
Conclusion
Let us know your thoughts in the comment section below.
Check out other publications to gain access to more digital resources if you are just starting out with Flux Resource.
Also contact us today to optimize your business(s)/Brand(s) for Search Engines
