Crafting Your First Ad Blocker Chrome Extension with React JS: A Beginner-Friendly Dive into Version 1

Crafting Your First Ad Blocker Chrome Extension with React JS: A Beginner-Friendly Dive into Version 1

ยท

2 min read

Step 1: Set Up a New React App

npx create-react-app ad-blocker-extension
cd ad-blocker-extension

Step 2: Create the Popup Component

Replace the contents of src/App.js with the following code:

import React from 'react';
import './App.css';

function App() {
  const blockAds = () => {
    // Logic to hide ad elements (for example, elements with class 'ad')
    const adElements = document.querySelectorAll('.ad');
    adElements.forEach(element => {
      element.style.display = 'none';
    });
  };

  return (
    <div className="App">
      <h1>Ad Blocker Extension</h1>
      <button onClick={blockAds}>Block Ads</button>
    </div>
  );
}

export default App;

Step 3: Styling (Optional)

You can add some basic styling to make your popup look better. Update src/App.css:

.App {
  text-align: center;
  padding: 20px;
}

button {
  padding: 10px 20px;
  font-size: 16px;
  cursor: pointer;
}

Step 4: Update Manifest File

Create a new file named public/manifest.json with the following content:

{
  "manifest_version": 2,
  "name": "Ad Blocker Extension",
  "version": "1.0",
  "description": "A simple ad blocker Chrome extension built with React JS.",
  "browser_action": {
    "default_popup": "index.html",
    "default_icon": {
      "16": "favicon.ico",
      "48": "favicon.ico",
      "128": "favicon.ico"
    }
  },
  "permissions": ["activeTab"]
}

Step 5: Build and Test

npm run build

Then, in Chrome:

  1. Open the Extensions page (chrome://extensions/).

  2. Enable "Developer mode" in the top right.

  3. Click "Load unpacked" and select the build folder inside your React app.

You should now see your extension icon in the Chrome toolbar. Click on it, and you'll see the popup with the "Block Ads" button.

When you visit a webpage with elements having the class "ad," clicking the "Block Ads" button should hide those elements.

Remember, this is a basic example, and a real-world ad blocker would need more sophisticated logic to identify and block ads effectively. Additionally, consider user preferences, options pages, and security aspects when developing a production-level extension.

ย