DeveloperBreeze

Creating a Chrome extension can be a fun and rewarding way to enhance your browsing experience or even contribute useful tools to the community. In this tutorial, we'll walk through the process of building a simple Chrome extension from scratch. By the end, you'll have a solid understanding of how Chrome extensions work and how you can create one.

What is a Chrome Extension?

A Chrome extension is a small software program that customizes your browsing experience. Extensions can modify and enhance the functionality of the Chrome browser, allowing users to personalize their browsing experience by adding new features, improving usability, and integrating with other services.

Prerequisites

Before we begin, make sure you have the following:

  • Basic knowledge of HTML, CSS, and JavaScript: This tutorial assumes you have a basic understanding of web development.
  • A text editor: Any text editor like Visual Studio Code, Sublime Text, or Atom will work.
  • Google Chrome browser: You'll need Chrome installed to test and run your extension.

Step 1: Setting Up the Project

First, let's create a directory for our Chrome extension. Open your terminal or file explorer and create a new folder:

mkdir my-chrome-extension
cd my-chrome-extension

Inside this folder, you'll create the necessary files for your extension.

Step 2: Create the manifest.json File

The manifest.json file is a required file for any Chrome extension. It provides essential information about the extension, such as its name, version, description, and permissions.

Create a manifest.json file in your project directory and add the following content:

{
  "manifest_version": 3,
  "name": "My Chrome Extension",
  "version": "1.0",
  "description": "A simple Chrome extension example.",
  "action": {
    "default_popup": "popup.html",
    "default_icon": {
      "16": "images/icon16.png",
      "48": "images/icon48.png",
      "128": "images/icon128.png"
    }
  },
  "permissions": [
    "activeTab"
  ]
}

Key Elements of the manifest.json File:

  • manifest_version: Specifies the version of the manifest file format. Version 3 is the latest and recommended version.
  • name: The name of your extension as it will appear in the Chrome Web Store and in the extension list.
  • version: The version of your extension, which must be updated with each new release.
  • description: A short description of what your extension does.
  • action: Defines the behavior of your extension's toolbar button, including the popup that will be displayed when clicked.
  • permissions: Specifies the permissions your extension needs to function. Here, activeTab allows the extension to interact with the current tab.

Step 3: Create the Popup HTML File

Next, let's create the popup that will appear when the user clicks the extension's icon in the toolbar.

Create a popup.html file in your project directory:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>My Chrome Extension</title>
  <link rel="stylesheet" href="popup.css">
</head>
<body>
  <div id="content">
    <h1>Hello, Chrome Extension!</h1>
    <button id="changeColor">Change Background Color</button>
  </div>
  <script src="popup.js"></script>
</body>
</html>

Explanation:

  • popup.html: This is a simple HTML file that contains a heading and a button. When the button is clicked, it will trigger a JavaScript function to change the background color of the current tab.

Step 4: Add Styling with CSS

To style your popup, create a popup.css file in the project directory:

body {
  font-family: Arial, sans-serif;
  width: 200px;
  padding: 10px;
}

h1 {
  font-size: 18px;
  color: #333;
}

button {
  background-color: #4CAF50;
  color: white;
  padding: 10px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  width: 100%;
}

button:hover {
  background-color: #45a049;
}

Explanation:

  • popup.css: This CSS file adds basic styling to the popup, making the button more visually appealing and the text easy to read.

Step 5: Add Interactivity with JavaScript

Now, let's add some interactivity to our extension using JavaScript. Create a popup.js file in your project directory:

document.getElementById('changeColor').addEventListener('click', () => {
  chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
    chrome.scripting.executeScript({
      target: { tabId: tabs[0].id },
      function: changeBackgroundColor
    });
  });
});

function changeBackgroundColor() {
  document.body.style.backgroundColor =
    document.body.style.backgroundColor === 'yellow' ? 'white' : 'yellow';
}

Explanation:

  • chrome.tabs.query: This API retrieves the active tab in the current window.
  • chrome.scripting.executeScript: Executes a script in the context of the active tab. In this case, it changes the background color of the webpage.

Step 6: Add Icons

For a complete extension, you'll need to add icons that represent your extension in the Chrome toolbar. Create an images folder in your project directory and add three icons with the following dimensions:

  • icon16.png (16x16 pixels)
  • icon48.png (48x48 pixels)
  • icon128.png (128x128 pixels)

You can create your own icons or use online tools like favicon.io to generate them.

Step 7: Load and Test Your Extension

With all the files in place, you're ready to load your extension into Chrome and test it.

  1. Open Chrome and navigate to chrome://extensions/.
  2. Enable "Developer mode" using the toggle switch in the upper right corner.
  3. Click "Load unpacked" and select your project directory (my-chrome-extension).
  4. Your extension should now appear in the list of installed extensions.

To test your extension:

  1. Click the extension icon in the Chrome toolbar.
  2. The popup should appear with a button.
  3. Click the "Change Background Color" button, and the background color of the current tab should toggle between yellow and white.

Step 8: Debugging and Improving Your Extension

Debugging:

  • Use chrome://extensions/ to inspect your extension and check for any errors.
  • Use Chrome DevTools to debug your extension's popup and content scripts.

Improving:

  • Add more features, such as saving the user's color preference.
  • Integrate with APIs to fetch data or interact with web services.
  • Add options to customize the extension via an options page.

Conclusion

Congratulations! You've successfully built a simple Chrome extension. This tutorial covered the basics of setting up a Chrome extension, including creating the manifest.json file, adding HTML, CSS, and JavaScript, and testing the extension in Chrome.

With this foundation, you can now explore more advanced features and build more complex extensions. Whether you want to enhance your browsing experience, create tools for developers, or just experiment with new ideas, Chrome extensions offer a powerful way to extend the functionality of the browser.

Continue Reading

Discover more amazing content handpicked just for you

Article

Mastering Modern Web Development: Trends, Tools, and Tutorials for 2025 and Beyond

Happy coding!

This article is part of our ongoing series on modern web development. Bookmark this page and subscribe to our newsletter for the latest updates, tutorials, and insights.

Feb 11, 2025
Read More
Tutorial
javascript css +1

How to Create a Chrome Extension for Automating Tweets on X (Twitter)

const tweets = [
  "https://developerbreeze.com/post/59",
  "https://anotheramazingresource.com",
  "https://yetanothergreatsite.com",
];

const engage = [
  "Check this out! πŸ”₯",
  "Learn something new today! πŸš€",
  "This is a must-read! πŸ“–",
];

Once you're satisfied with your extension, you can share it or publish it on the Chrome Web Store.

Dec 10, 2024
Read More
Article

Integrating Flowbite with Tailwind CSS: A Step-by-Step Tutorial

   npm init -y

This command generates a package.json file with default configurations, which will manage your project's dependencies.

Oct 24, 2024
Read More
Cheatsheet

Front-End Development Tools and Libraries Cheatsheet

Introduction

Front-end development has evolved significantly, with a plethora of tools and libraries available to enhance productivity and build responsive, interactive web applications. This cheatsheet covers the most essential and popular tools and libraries for front-end developers, organized by category.

Aug 21, 2024
Read More
Cheatsheet
javascript

React Performance Optimization Cheatsheet: Hooks, Memoization, and Lazy Loading

import React, { useState, useCallback } from 'react';

function ParentComponent() {
  const [count, setCount] = useState(0);

  const increment = useCallback(() => {
    setCount((prevCount) => prevCount + 1);
  }, []);

  return (
    <div>
      <ChildComponent onClick={increment} />
      <p>Count: {count}</p>
    </div>
  );
}

function ChildComponent({ onClick }) {
  console.log('Child component re-rendered');
  return <button onClick={onClick}>Increment</button>;
}

Here, useCallback prevents the increment function from being recreated on every render, which in turn prevents the ChildComponent from unnecessary re-renders.

Aug 20, 2024
Read More
Tutorial
javascript php

Integrating Laravel and React with Vite: Using Databases and PHP in a Full-Stack Project

Run the migration to create the table:

php artisan migrate

Aug 14, 2024
Read More
Tutorial

Integrating Vite with Laravel for Modern Web Development

If you don't already have a Laravel project, create one using Composer:

   composer create-project laravel/laravel my-vite-laravel-app

Aug 14, 2024
Read More
Tutorial

Getting Started with Vite: A Fast Frontend Build Tool

   <template>
     <div>
       <h1>Hello, Vite + Vue!</h1>
     </div>
   </template>

   <script>
   export default {
     name: 'App',
   };
   </script>

When your project is ready to be deployed, you can build it for production:

Aug 14, 2024
Read More
Code
javascript

React Custom Hook for API Requests

Here’s an example of how to use the useFetch hook in a React component to fetch and display data.

import React from 'react';
import useFetch from './useFetch'; // Ensure correct import path

function UserList() {
    const { data, loading, error } = useFetch('https://jsonplaceholder.typicode.com/users');

    if (loading) return <p>Loading...</p>;
    if (error) return <p>Error: {error.message}</p>;

    return (
        <ul>
            {data.map(user => (
                <li key={user.id}>{user.name}</li>
            ))}
        </ul>
    );
}

export default UserList;

Aug 12, 2024
Read More
Tutorial
css

Building Responsive Web Designs with Tailwind CSS

You should have a basic understanding of HTML and CSS. Make sure you have Node.js and npm installed on your machine, as we will use them to set up Tailwind CSS.

Open your terminal and create a new project directory:

Aug 05, 2024
Read More
Tutorial
javascript

Building a Modern Web Application with React and Redux

   npx create-react-app my-react-app

This command will create a new directory called my-react-app with all the necessary files and dependencies.

Aug 05, 2024
Read More
Note
javascript css +1

Automatically add Tailwind CSS and jQuery classes to any table

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Table Styling with Tailwind CSS</title>
    <!-- Include Tailwind CSS -->
    <link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet">
    <!-- Include jQuery -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>

<!-- Example table -->
<table>
    <thead>
        <tr>
            <th>Header 1</th>
            <th>Header 2</th>
            <th>Header 3</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Data 1</td>
            <td>Data 2</td>
            <td>Data 3</td>
        </tr>
        <tr>
            <td>Data 4</td>
            <td>Data 5</td>
            <td>Data 6</td>
        </tr>
    </tbody>
</table>

<!-- jQuery script to apply classes -->
<script>
    $(document).ready(function() {
        $('table').each(function() {
            $(this).addClass('min-w-full bg-white border border-gray-200');
            $(this).find('thead').addClass('bg-gray-50');
            $(this).find('th').addClass('px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider border-b border-gray-200');
            $(this).find('tbody').addClass('bg-white divide-y divide-gray-200');
            $(this).find('tr').addClass('hover:bg-gray-100');
            $(this).find('td').addClass('px-6 py-4 whitespace-nowrap text-sm text-gray-900');
        });
    });
</script>

</body>
</html>

The <link> tag includes Tailwind CSS via CDN, enabling use of utility classes.

Aug 03, 2024
Read More
Browser Mockup 1
Tailwind Component

Browser Mockup 1

No preview available for this content.

Jan 26, 2024
Read More

Discussion 0

Please sign in to join the discussion.

No comments yet. Start the discussion!