Building a browser (Edge) extension

Rohit Shirke
6 min readMar 14, 2023

--

Browser extension

Browser extensions are nothing new to introduce. Everyone must have used some extensions at some point in time. some popular ones are Grammarly, adblocker and more. The extensions that we use are typically complex and do multiple things. In this article, we will have a look at basic building block of a browser extension. We will build a simple extension that clean user browser cache & cookies for edge browser.

So, lets dive in,

What are we building?

We would be building a simple extension that will allow us to quickly clear any cookies and browser cache for a website.

Why Edge?

Edge is chromium-based browser from Microsoft and offer pretty much the same functionality of the chrome (Even better). Extensions that work with Edge will work with chrome*.

Edge has separate extension store where you can publish the extensions free of cost. where on chrome app store you need to pay $5 fees one-time fees post which you can publish 20 extensions)

As this was just an experiment I went with edge! 😁

Anything I need to know in advance?

Since, the code we would be writing would be written in JavaScript a basic understanding of the same will be helpful. Even if you don’t understand it, follow along & I will try my best to explain the stuff.

Code structure:

Extension structure Source: Chrome-docs

The image above depicts the code structure. Let's look at each of them one by one.

manifest.json : This is the core file that defines the basic details of your extension, behaviour for your extension, any permission that your extension will use and finally the icons.

{
"name": "Name of extension",
"author": "author name",
"version": "1.0",
"manifest_version": 3,
"permissions": ["permission 1", "permission 2" ],
"background": {
"service_worker": "background.js"
},
"action": {
"default_popup": "popup.html",
"default_icon": {
"16": "icons/icon-16.png",
"32": "icons/icon-32.png",
"48": "icons/icon-48.png",
"64": "icons/icon-64.png",
"128": "icons/icon-128.png"
}
},
"icons": {
"16": "icons/icon-16.png",
"32": "icons/icon-32.png",
"48": "icons/icon-48.png",
"64": "icons/icon-64.png",
"128": "icons/icon-128.png"
},
"host_permissions": ["https://*/*","http://*/*"]
}

Many attributes in this file are self-explanatory. let's try to understand them.

  • Name : This will be the name of your extension. This name will be shown for your extension in app store and in the browser extension list.
  • Author : Name of the author or organization.
  • Version: This define the extension version number.
  • Manifest Version: This is an important filed that defines the manifest version number you are following. The newly supported version is version 3 and you should avoid using version 2
  • Permissions: These are list of permissions that will be used by your extension. Here is a full list of permissions you can use
    Supported APIs for Microsoft Edge extensions — Microsoft Edge Development | Microsoft Learn
  • Background: This object specify the path to any service worker file that we want to associate.
  • Action: This object specifies the default behaviour of our extension. Since we are using a seperate page for our extension we would set the default_popup property on this object with the path to the file we want to associate. (eg. popup.html). We will also set the default icon set to be used by the extenstion here.
  • Icons: This object will specify the variety of icons that will be used by the extension based on the system resolution.
  • Host Permissions: Since we want our extension to only work on sites with http and https prefix, we apply that as a rule here. This allows us to specify a pattern e.g specific domain on which the extension will work else it wont. here we will stick with (https://*/* and http://*/* ) which signify on all sites starting with http and https.

Let's look at the other files from the file directory.

background.js: This file is used to define the script that you want to run in background (service worker) (Optional)

scripts: This directory can be used to hold any extra script that your extension might use. (Optional)

Popup: Again, this is just way to organize the code. You can have any name to this folder. This will be used to keep any files that your extension might render (Consider it as simple web page with its own scripts and css) (Optional) If your extension doesn’t have any visual elements apart from the extension icon you might not even have this.

Images: This directory will hold any icons that your extension will use. (Optional) you can keep images at the root itself.

Now as you have the basic understanding of the files and the structure we can start working..
Since we are building an extension that will allow user to clean browser data, cookies and application data, lets define basic structure for the extension.

  • We will have three buttons each for clearing cookie, cache and Storage (Session Storage + local storage).
  • When the user will click each button, we would perform the required action.
  • & Finally, we will show a message to the use in a label.
Cache extension

Below are the permissions we would need.

"activeTab", "cookies", "storage","tabs","browsingData","scripting"
  • Active tab & Tab: allow us to interact with current tab and tabs in general.
  • Cookies: Allow to interact with cookies.
  • Storage: Allow us to work with
  • Browsing Data: Allow us to interact with application storage.
  • Scripting: Allow us to execute arbitory scripts.

Below is the HTML where page that will be shown as popup when you click on the extension icon in the browser. Here we have created three buttons with unique id’s that will be used to hook the events.

<!DOCTYPE html>
<html>
<head>
<title>Clear Cookies and Cache</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<table>
<tr>
<td class="text-left">Cookies</td>
<td class="text-right"><button id="clearCookiesBtn"> &#128465; </button></td>
</tr>
<tr>
<td class="text-left">Session</td>
<td class="text-right"><button id="clearCacheBtn">&#128465;</button></td>
</tr>
<tr>
<td class="text-left">Storage</td>
<td class="text-right"><button id="clearStorageBtn">&#128465;</button></td>
</tr>
<tr>
<td class="text-left">Reload Page</td>
<td class="text-right"><button id="reloadeBtn">&#8634;</button></td>
</tr>
</table>
<hr>
<span id = "message"></span>
<script src="popup.js"></script>
</body>
</html>


Let's look at the event handing code. For simplicity let's look at one function.

  • Register the event listener for the cookie.
document.getElementById('clearCookiesBtn').addEventListener('click', clearCookies);
  • Let's look at the handler function.
function clearCookies() {
chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
chrome.cookies.getAll({ url: tabs[0].url }, function (cookies) {
for (var i = 0; i < cookies.length; i++) {
chrome.cookies.remove({ url: tabs[0].url + cookies[i].path, name: cookies[i].name });
}
showMessage("Cookies cleared.");
});
});
}
  • The chrome.tabs.query function return list of tabs queried. Here we pass the filter active and current window arguments to function to indicate the current tab. This will return the result as array (list of tabs). now we iterate over the tab array.
  • Now for each tab we try to retrieve the cookies associated with the tab (Site loaded in tab) with chrome.cookies.getAll and finally we use the chorme.cookies.remove function to specify the URL and cookie name to be removed.
  • Finally, we show user a message about the result.

The cache function is also implemented similar way. The only difference is we iterate over the Browsing data object instead of the cookies.

IMP: For local storage and application storage we are taking a different approach. To as the to get the local storage and application storage are associated with the window object and if we try to execute the script like cookies or browsing data it executes in the current page context whiz is our pop-up.html. Below code does exactly that.

function clearStorage() {
chrome.tabs.query({ active: true, currentWindow: true }, function(tabs) {
var currentTab = tabs[0];
chrome.scripting.executeScript({
target : { tabId : currentTab.id },
func : clearAppData,
}).then(() => {
showMessage("Local & Session Storage cleared.");
});
});
}

// Clear data function for call
function clearAppData(){
window.localStorage.clear();
window.sessionStorage.clear();
}

Below is the full implementation of the poup.js

And Congratulation we have a basic extension ready.

Here is the link to public repository for the extension.
shirkerohit/dev-helper-extension-chromium: Simple extension to clean cookies, cache and session storage. (github.com)

Testing:

Here is simple guide from Microsoft docs Sideload an extension — Microsoft Edge Development | Microsoft Learn

Once the extension is sideloaded, you can simply click on the extension from the browser extension list to activate it and if you have followed the steps correctly, your extension should work as expected.

That’s it!

Here is the link to extension published. Do give it a try.

https://microsoftedge.microsoft.com/addons/detail/clear-cache-and-cookies/opajfeocnjojgpdgmhofmnlijckgpndk

Hope this helped you to understand the basics of browser extension. Seeya until next post!

Happy coding! 😄

--

--