0% found this document useful (0 votes)
48 views7 pages

Browser

This tutorial explains how to build a website blocker browser extension that can run on multiple browsers like Chrome, Opera, Brave and Edge. The extension allows users to add websites to a block list that they do not want to access. When users try to visit a blocked site, a message will be displayed denying access. The extension is built using HTML, CSS, JavaScript and the browser API. It has options to view and manage the blocked site list.

Uploaded by

aashwini kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
48 views7 pages

Browser

This tutorial explains how to build a website blocker browser extension that can run on multiple browsers like Chrome, Opera, Brave and Edge. The extension allows users to add websites to a block list that they do not want to access. When users try to visit a blocked site, a message will be displayed denying access. The extension is built using HTML, CSS, JavaScript and the browser API. It has options to view and manage the blocked site list.

Uploaded by

aashwini kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

How To Developers

Building a Website Blocker


Extension in Minutes

This tutorial
explains how you
can build a website
blocker extension
that will run on
multiple browsers.

W
eb browsers have become integral to our Tokens to websites and content creators. You can download
lives, and are used on a wide range of devices, Brave from https://brave.com/download/.
including desktops, laptops, tablets and ƒƒ Microsoft Edge: This is a Web browser developed by
smartphones. In 2019, an estimated 4.3 billion Microsoft. It was rebuilt as a Chromium based browser in
people used Web browsers. The most used browser today is 2019. It is also available for Windows, Android, iOS and
Google Chrome, with a 64 per cent global market share across MacOS. You can download Microsoft Edge from https://
all devices, followed by Apple Safari with 17 per cent. www.microsoft.com/en-us/edge.

A few popular Web browsers What is a browser extension?


ƒƒ Google Chrome: This popular cross-platform Web A browser extension is a small software module that
browser has been developed by Google. It was first customises or adds extra functionality to the browser.
released in 2008 for the Windows platform and was This extension enhances or adds some extra features to
later ported to Linux, MacOS, iOS and Android. You the browser. The extensions are mostly written using Web
can download Google Chrome from https://www. technologies like HTML, JavaScript and CSS. They are
google.com/chrome/. hosted on vendor specific stores. For example, Chrome
ƒƒ Opera: This is a freeware browser for Windows, Android, extensions are hosted on the Chrome Web Store, Mozilla
iOS, MacOS and Linux, developed by Opera Software. It is Firefox hosts its extensions on its extension store, and so
a Chromium based browser using the Blink layout engine. on. Users can go to the store of the browser they are using
What differentiates it from other browsers is a unique user to download and install any of the wide variety of browser
interface, and a few other features. You can download extensions available there.
Opera from https://www.opera.com/hi/download.
ƒƒ Brave: This is a free and open source Web browser Creating an extension
developed by Brave Software Inc., based on the Chromium We are now going to build a website blocker extension,
framework. This browser has ad-blocking and website which will run on multiple Web browsers (Google Chrome,
tracker-blocking features inbuilt. It also allows users to send Opera, Brave and Microsoft Edge). This extension will
cryptocurrency contributions in the form of Basic Attention allow users to block websites in a browser. Users can add

www.OpenSourceForU.com | OPEN SOURCE For You | april 2020 | 97


Developers How To

the website they want to block to the list. When they try ƒƒ block.js: In this file we are going to intercept the outgoing
to visit that site, a message that states that the website is request from the browser. If the request contains one
blocked will be displayed, and access to it will be denied. If of the blocked websites from the list, we will reject the
the users then want to visit the site, they will have to unblock request, thus blocking that website.
it by deleting the website entry from the list of blocked ƒƒ style.css adds styles to the options.html page to
sites in the extension. make it look good.
We are going the use the following Web technologies to
build this extension: Creating the manifest file
ƒƒ HTML to create a table to view blocked sites, and buttons Open the manifest.json file and copy the following
to add and delete them JSON code:
ƒƒ CSS to style HTML
ƒƒ JavaScript (Chrome browser API) to write our logic {
“name”: “Website Blocker”,
Setting up the development environment “version”: “1.0.0”,
Let us now set up the file structure for our browser extension. “description”: “Blocks websites based on domain names”,
Create a new folder and give it a name, say ‘web-blocker’. “background”: { “scripts”: [“block.js”] },
Now, inside that folder, create the following empty files: “options_page”: “options.html”,
ƒƒ manifest.json “permissions”: [
ƒƒ options.html “webRequest”, “webRequestBlocking”,
ƒƒ script.js “http://*/*”, “https://*/*”,
ƒƒ block.js “storage”
ƒƒ style.css ],
You should end up with the directory structure shown in “manifest_version”: 2
Figure 1. }
ƒƒ manifest.json is a metadata file in JSON format. It
contains basic information about the extension, like its As you can see, this code is in JSON format. It consists
name, a description of it, the version number, which script of general information about the browser extension, such as
it should run on starting up, etc. its version, name, description, permissions required for the
ƒƒ options.html displays the UI of the extension, like the extension, and so on.
list of websites to be blocked, buttons to add and delete, The parameter description is as follows:
websites from the list, etc. ƒƒ manifest_version specifies the version of the manifest; the
ƒƒ script.js controls the interactions and the logic of the value must be 2
options.html file. ƒƒ name specifies the name of the extension
ƒƒ version specifies the version of the extension
ƒƒ description specifies a short description of the extension
ƒƒ background specifies that the script block.js should load as
soon as the user starts the browser
ƒƒ options_page specifies the UI page to be displayed for
extension options
ƒƒ permission specifies which browser APIs are to be
used. We are using webRequest, webRequestBlocking,
https://*/*, http://*/* and storage

Note: It is assumed that you have some basic


knowledge of Web technologies like HTML, CSS
and JavaScript. If you don’t, W3Schools (http://www.
w3schools.com/) is a good place to start. The site has some
great tutorials for Web technologies that are easy to follow.

To add HTML, open the options.html file located in the


Figure 1: Extension project file structure extension directory, and add the following HTML code:

98 | april 2020 | OPEN SOURCE For You  | www.OpenSourceForU.com


How To Developers

<!DOCTYPE html> width: 300px;


<html> padding: 10px;
<head> margin: 10px;
<meta charset=”utf-8”> border-radius: 4px;
<meta http-equiv=”X-UA-Compatible” content=”IE=edge”> outline: none;
<title></title> border: 1px solid #eee;
<meta name=”description” content=””> }
<meta name=”viewport” content=”width=device-width,
initial-scale=1”> #add {
<link rel=”stylesheet” href=”style.css”> border: none;
</head> border-radius: 50%;
<body> background-color: #0081cb;
<div class=”header”> color: #ffffff;
<input class=”add-website” type=”url” cursor: pointer;
placeholder=”Enter Website e.g: https://www.example.com”> width: 26px;
<button id=”add”>+</button> height: 26px;
</div> cursor: pointer;
<div class=”main”> }
<table>
<tr> .delete {
<th>Websites Blocked</th> border: none;
</tr> border-radius: 50%;
<tr id=”no-website-msg”> background-color: #e6463b;
<td>No websites blocked yet.</td> color: #ffffff;
</tr> cursor: pointer;
</table> width: 26px;
</div> height: 26px;
<script src=”script.js” defer></script> cursor: pointer;
</body> float: right;
</html> margin-right: 6px;
margin-top: 10px;
In the above HTML code, we have added the following }
elements:
ƒƒ <input> - The user will enter the website to be blocked in table {
this input field height: auto;
ƒƒ <button> - To add and delete websites added to the list width: 388px;
ƒƒ <table> - To display the list of blocked/added websites }
To add CSS styles, use the following code:
table tr th {
body { border-bottom: 1px solid #0081cb;
font-family: ‘Segoe UI’, Tahoma, Geneva, Verdana, sans- padding: 5px;
serif; }
margin: 0;
padding: 0; table td {
box-sizing: border-box; padding: 8px;
display: flex; line-height: 32px;
justify-content: center; width: 100%;
align-items: center; }
flex-direction: column;
} table td {
border-bottom: 1px solid #e2e2e2;
.add-website { }

www.OpenSourceForU.com | OPEN SOURCE For You | april 2020 | 99


Developers How To

} else {
urls = [];
}
});
addButton.addEventListener(‘click’, function () {
const url = document.getElementsByClassName(‘add-
website’)[0].value;
if (url.length > 0) {
noWebsiteMsg.style.display = “none”;
Figure 2: Website blocker user interface urls.push(url + “/*”);
chrome.storage.local.set({
This CSS will style the UI as shown in Figure 2. “websites”: JSON.stringify(urls)
To add JavaScript, open the script.js file and copy the }, function (value) {
following JavaScript code: console.log(value);
});
let urls = []; // Global variable to store URLs save();
loadList();
// Load init when the content is loaded. document.getElementsByClassName(‘add-website’)
window.addEventListener(‘DOMContentLoaded’, init); [0].value = “”;
window.addEventListener(‘DOMContentLoaded’, loadList); }
});
//Init Function - Initialize, load, addEventListeners }
function init() {
const addButton = document.getElementById(‘add’); function loadList() {
const deleteButton = document.getElementsByClassName(‘de const deleteButton = document.getElementsByClassName(‘de
lete’); lete’);
const noWebsiteMsg = document.getElementById(‘no-website- const tblNode = document.getElementsByTagName(‘body’)[0];
msg’); let tblRow = document.createElement(‘tr’);
chrome.storage.local.getBytesInUse([‘websites’], function let tblData = document.createElement(‘td’);
(bytes) { let tblButton = document.createElement(‘button’);
if (bytes) { let storedURLs = [];
chrome.storage.local.get(“websites”, function chrome.storage.local.getBytesInUse([‘websites’], function
(res) { (bytes) {
if (res != {}) { if (bytes) {
urls = JSON.parse(res.websites); chrome.storage.local.get(“websites”, function
if (urls == undefined || urls.length == (res) {
0) { if (res != {}) {
noWebsiteMsg.style.display = “”; storedURLs = JSON.parse(res.websites);
} else {
noWebsiteMsg.style.display = “none”; if (storedURLs != undefined || storedURLs
} != []) {
if (deleteButton) { for (let i = 0; i < storedURLs.
for (let i = 0; i < deleteButton. length; i++) {
length; i++) { tblButton.innerText = “-”;
deleteButton[i]. tblButton.setAttribute(‘class’,
addEventListener(‘click’, function (e) { ‘delete’);
deleteWebsite(e); tblRow.setAttribute(‘id’, “row” + i);
}); tblButton.setAttribute(‘id’, i);
} tblData.innerText =
} storedURLs[i];
} tblRow.appendChild(tblData);
}); tblRow.appendChild(tblButton);

100 | april 2020 | OPEN SOURCE For You  | www.OpenSourceForU.com


How To Developers

document. We have used Chrome’s storage API to store the website


getElementsByTagName(‘table’)[0].appendChild(tblRow); list.
if (deleteButton) { Now open the block.js file and copy the following
JavaScript code:
deleteButton[i].
addEventListener(‘click’, function (e) { function blockRequest() {
deleteWebsite(e); return {
}); cancel: true
};
} }
} chrome.extension.onRequest.addListener(
} function (request, sender, sendResponse) {
if (request.urls == ‘save’) {
} let getStoredURLs = [];
}); chrome.storage.local.getBytesInUse(‘websites’,
function (bytes) {
} else { if (bytes) {
storedURLs = []; chrome.storage.local.get(“websites”,
} function (res) {
}); if (res != {}) {
getStoredURLs = JSON.parse(res.
} websites);
if (getStoredURLs.length > 0) {
function deleteWebsite(e) { const filter = {
urls.splice(e.target.id, 1); urls: getStoredURLs,
chrome.storage.local.set({ };
“websites”: JSON.stringify(urls) chrome.webRequest.
}, function () {}); onBeforeRequest.addListener(
if (document.getElementById(“row” + e.target.id)) blockRequest,
document.getElementById(“row” + e.target.id). filter, [“blocking”]
remove(); );
save(); } else if (getStoredURLs.length
init(); == 0) {
}
if (chrome.webRequest.
function save() { onBeforeRequest.hasListener(blockRequest)) {
chrome.extension.sendRequest({ chrome.webRequest.
urls: “save” onBeforeRequest.removeListener(blockRequest);
}, function (response) { }
}
}); }
} });
} else {
Here, we have declared four functions: init(), loadList(), getStoredURLs = false;
deleteWebsite() and save(). }
ƒƒ init() initialises all the HTML elements, and here we can });
also add event listeners for buttons }
ƒƒ loadList() loads the list of websites we have added/deleted }
to and from the list );
ƒƒ deleteWebsite() deletes the website from the list
ƒƒ save() saves the websites we have added to the list, into Here, we intercept the Web request made using chrome.
storage

www.OpenSourceForU.com | OPEN SOURCE For You | april 2020 | 101


Developers How To

Figure 3: Extension loader interface to load/unload extensions

Figure 4: Folder selection dialogue box to select our extension

webRequest.onBeforeRequest API and check if it matches the corner, if it hasn’t been checked.
list of websites that we have stored. If it does, we block the 3. Now, click on Load unpacked, which will open up the file-
request; else, we allow it. selection dialogue box, as shown in Figure 4.
4. Navigate to the directory where your extension files
Loading the extension are and select it. Another easy way is to simply drag
First, let us load the extension in the Chrome browser. and drop the extension folder onto chrome://extensions
1. Open up the Chrome menu by clicking the icon that’s to in your browser to load it. The extension will install/
the right of the address bar and select Extensions under load right away. If you make some errors while creating
the Tools menu or just enter chrome://extensions in the the extension, it will not load and will display an error
address bar before hitting Enter, as shown in Figure 3. message at the top of the page. You have to rectify the
2. Check the Developer mode checkbox in the top right-hand error and then try again.

102 | april 2020 | OPEN SOURCE For You  | www.OpenSourceForU.com


How To Developers

Figure 5: Our extension in the top-right corner of the browser

the context menu. Then select Options, which will open the
options page. Here you can add the website you want to
block. As an example, I added https://www.facebook.com
to the list, as shown in Figure 6; so as soon as I try to visit
https://www.facebook.com, the request gets blocked and a
message is displayed, as shown in Figure 7. Now, the website
is blocked, unless I delete it from the list.

Testing the extension in the Opera, Brave and


Figure 6: Website blocker list shown by the extension Microsoft Edge browsers
In Opera, navigate to opera://extensions. In Brave, navigate to
brave://extensions and in Edge, navigate to edge://extensions.
Then, enable Developer Mode and follow the same steps that
you did for Google Chrome.

Note: You can also refer to and download this project’s


source code from my GitHub repository. Visit https://
github.com/aniketkudale/website-blocker.

References
[1] https://www.google.com/chrome/
[2] https://developer.chrome.com/extensions/api_index
Figure 7: The extension blocking the request to a website

Running the extension By: Aniket Eknath Kudale


After installing/loading the extension, you can test it by The author is a senior member of the technical staff at TIBCO
right-clicking the extension icon shown at the top-right corner Software Inc., Pune, with more than five years’ experience. His
interests include Web technologies, computer vision and security.
near the address bar, as shown in Figure 5. This will show

www.OpenSourceForU.com | OPEN SOURCE For You | april 2020 | 103

You might also like