Building a Chrome Extension to Block URLs with a Blacklist API
Image by Tannya - hkhazo.biz.id

Building a Chrome Extension to Block URLs with a Blacklist API

Posted on

As a developer, I’m excited to share my journey of creating a Chrome extension that blocks unwanted URLs based on a dynamically fetched blacklist from an API. In this article, I’ll walk you through the entire process, from conceptualization to implementation, so you can build your own extension that keeps the internet a safer and more pleasant place.

What You’ll Need

Before we dive into the tutorial, make sure you have the following essentials:

  • A basic understanding of JavaScript, HTML, and CSS
  • Google Chrome browser installed on your system
  • A code editor or IDE of your choice (e.g., Visual Studio Code, Sublime Text)
  • An API that provides a blacklist of URLs (you can use a dummy API or create your own)

Step 1: Create the Directory Structure and Files

Let’s start by creating a new directory for our project and adding the necessary files:

mkdir url-blocker-chrome-extension
cd url-blocker-chrome-extension
touch manifest.json
mkdir scripts
touch scripts/background.js
mkdir html
touch html/popup.html
mkdir css
touch css/popup.css

The directory structure should look like this:

Directory/File Description
manifest.json The Chrome extension manifest file
scripts Folder containing the background script
background.js The script that will fetch the blacklist API and block URLs
html Folder containing the popup HTML file
popup.html The HTML file for the popup that will display the blocked URLs
css Folder containing the popup CSS file
popup.css The CSS file for styling the popup

Step 2: Configure the Manifest File

In the `manifest.json` file, add the following content:

{
  "manifest_version": 2,
  "name": "URL Blocker",
  "version": "1.0",
  "description": "A Chrome extension that blocks URLs based on a blacklist API",
  "permissions": ["activeTab", "https://api.example.com/*"],
  "background": {
    "scripts": ["scripts/background.js"]
  },
  "browser_action": {
    "default_popup": "html/popup.html"
  }
}

This manifest file declares the basic metadata for our extension, specifies the permissions required, and defines the background script and popup HTML file.

Step 3: Fetch the Blacklist API and Block URLs

In the `background.js` file, add the following code:

fetch('https://api.example.com/blacklist')
  .then(response => response.json())
  .then(data => {
    const blacklist = data.urls;
    chrome.webRequest.onBeforeRequest.addListener(
      function(details) {
        if (blacklist.includes(details.url)) {
          return { cancel: true };
        }
      },
      { urls: [""] },
      ["blocking"]
    );
  });

This script fetches the blacklist API, extracts the URLs from the response, and uses the `chrome.webRequest` API to block any requests to URLs found in the blacklist.

Step 4: Create the Popup HTML and CSS

In the `popup.html` file, add the following content:

<!DOCTYPE html>
<html>
  <head>
    <link rel="stylesheet" href="css/popup.css">
  </head>
  <body>
    <h1>Blocked URLs</h1>
    <ul id="blocked-urls"></ul>
    <script src="scripts/popup.js"></script>
  </body>
</html>

In the `popup.css` file, add the following styles:

body {
  font-family: Arial, sans-serif;
  width: 200px;
  height: 100px;
  text-align: center;
  padding: 20px;
  border: 1px solid #ccc;
  border-radius: 5px;
  box-shadow: 0px 0px 10px rgba(0,0,0,0.5);
}

h1 {
  margin-top: 0;
}

ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

li {
  padding: 10px;
  border-bottom: 1px solid #ccc;
}

li:last-child {
  border-bottom: none;
}

Step 5: Update the Popup with Blocked URLs

In the `popup.js` file, add the following code:

chrome.webRequest.onCompleted.addListener(
  function(details) {
    if (details.statusCode === 403) {
      const blockedUrl = details.url;
      const dataList = document.getElementById("blocked-urls");
      const listItem = document.createElement("li");
      listItem.textContent = blockedUrl;
      dataList.appendChild(listItem);
    }
  },
  { urls: [""] },
  ["responseHeaders"]
);

This script listens for completed web requests and checks if the status code is 403 (Forbidden). If so, it appends the blocked URL to the popup’s list.

Step 6: Load the Extension in Chrome

To test our extension, go to the Chrome extensions page by typing `chrome://extensions/` in the address bar. Enable developer mode and click “Load unpacked.” Then, select the directory containing our extension’s files.

Conclusion

That’s it! We’ve successfully built a Chrome extension that blocks URLs based on a dynamically fetched blacklist from an API. You can now customize the extension to fit your needs, such as adding a user interface to manage the blacklist or integrating with other services.

If you’re interested in publishing your extension, follow the instructions on the Chrome Web Store Developer Dashboard to create a developer account and upload your extension.

Remember to always follow the Chrome extension policies and guidelines to ensure your extension remains compliant and safe for users.

Final Thoughts

Building a Chrome extension that blocks URLs with a blacklist API is a powerful way to help users avoid unwanted content. By following this tutorial, you’ve gained hands-on experience with Chrome extension development and API integration.

Don’t be afraid to experiment and push the boundaries of what’s possible with Chrome extensions. Happy coding, and I hope you’ll join me in the fight against unwanted URLs!

I’m developing a Chrome extension that aims to block URLs based on a blacklist fetched from an API. If you have any questions or need further assistance, feel free to ask in the comments below.

Additional Resources

For further reading and exploration, I recommend the following resources:

Stay tuned for more tutorials and articles on Chrome extension development and API integration. Happy coding!

Frequently Asked Question

Get answers to your burning questions about developing a Chrome extension that blocks URLs based on a blacklist fetched from an API!

Q: What’s the main purpose of your Chrome extension?

A: The main purpose of my Chrome extension is to block URLs that are listed on a blacklist fetched from an API. This way, users can avoid accessing malicious or unwanted websites!

Q: How does your Chrome extension get the blacklist from the API?

A: Ah, great question! My Chrome extension sends a request to the API to fetch the blacklist, which is then stored locally for future reference. This way, the extension can efficiently block URLs without having to query the API for every single website visit!

Q: Will your Chrome extension slow down my browsing experience?

A: Not at all! Since the blacklist is stored locally, the extension only needs to check the URL against the local list, which happens in a snap! You won’t notice any significant delay in your browsing experience.

Q: Can I customize the blacklist or add my own URLs to block?

A: Absolutely! My Chrome extension allows users to add their own custom URLs to block, giving them more control over their browsing experience. Simply add the URL to the custom blocklist, and the extension will take care of the rest!

Q: Is your Chrome extension compatible with other ad blockers and browser extensions?

A: Yep! My Chrome extension is designed to play nice with other ad blockers and browser extensions. You can use it alongside your favorite ad blockers or extensions without any issues!