Creating a Color Changer Chrome Extension
This tutorial will guide you through creating a Chrome extension that changes the background color of web pages and keeps track of how many times the color has been changed.
Step 1: Set Up the Folder Structure
First, create a new folder for your extension with the following structure:
my-extension/
│
├── manifest.json
├── background.js
├── popup/
│ ├── popup.html
│ └── popup.js
└── content_scripts/ └── content.js
Step 2: Create the Manifest File
The manifest.json
file is the heart of your Chrome extension. It tells Chrome about your extension, its capabilities, and the files it needs to function.
Create a file named manifest.json
in the root of your extension folder with the following content:
{ "manifest_version": 3, "name": "Color Changer", "version": "1.0", "description": "Changes webpage background color", "permissions": ["activeTab", "storage"], "background": { "service_worker": "background.js" }, "content_scripts": [ { "matches": ["<all_urls>"], "js": ["content_scripts/content.js"] } ], "action": { "default_popup": "popup/popup.html" }
}
Explanation:
-
manifest_version
: Specifies we’re using Manifest V3, the latest version for Chrome extensions. -
permissions
: Requests access to the active tab and storage API. -
background
: Specifies the background script file. -
content_scripts
: Defines which script should be injected into web pages. -
action
: Specifies the HTML file for the extension’s popup.
Step 3: Create the Popup HTML
Create a file named popup.html in the popup folder:
<!DOCTYPE html>
<html>
<head> <title>Color Changer</title> <style> body { width: 200px; padding: 10px; } button { width: 100%; padding: 5px; margin-bottom: 10px; } </style>
</head>
<body> <button id="changeColor">Change Color</button> <p>Color changed <span id="count">0</span> times</p> http://popup.js
</body>
</html>
This creates a simple popup with a button and a counter. I’ve added some basic CSS to improve the layout.
Step 4: Create the Popup JavaScript
Create a file named popup.js in the popup folder:
document.addEventListener('DOMContentLoaded', function() { var changeColor = document.getElementById('changeColor'); var countSpan = document.getElementById('count'); // Load the current count chrome.storage.sync.get('colorCount', function(data) { countSpan.textContent = data.colorCount || 0; }); changeColor.addEventListener('click', function() { chrome.tabs.query({active: true, currentWindow: true}, function(tabs) { chrome.tabs.sendMessage(tabs[0].id, {action: "changeColor"}, function(response) { console.log(response); }); }); // Increment the count chrome.storage.sync.get('colorCount', function(data) { var newCount = (data.colorCount || 0) + 1; chrome.storage.sync.set({colorCount: newCount}); countSpan.textContent = newCount; }); // Notify background script chrome.runtime.sendMessage({action: "colorChanged"}); });
});
Explanation:
- We wait for the DOM to load before attaching event listeners.
- We retrieve the current color change count from storage and display it.
When the button is clicked, we:
- Send a message to the content script to change the page color.
- Increment the color change count and update it in storage and on the popup.
- Send a message to the background script to log the change.
Step 5: Create the Background Script
Create a file named background.js in the root of your extension folder:
chrome.runtime.onInstalled.addListener(function() { chrome.storage.sync.set({colorCount: 0});
}); chrome.runtime.onMessage.addListener( function(request, sender, sendResponse) { if (request.action === "colorChanged") { console.log("Background color was changed"); } }
);
Explanation:
- When the extension is installed, we initialize the color count to 0.
- We listen for messages from other parts of the extension. When a “colorChanged” message is received, we log it to the console.
Step 6: Create the Content Script
Create a file named content.js in the content_scripts folder:
chrome.runtime.onMessage.addListener( function(request, sender, sendResponse) { if (request.action === "changeColor") { document.body.style.backgroundColor = getRandomColor(); sendResponse({status: "Color changed"}); } }
); function getRandomColor() { var letters = '0123456789ABCDEF'; var color = '#'; for (var i = 0; i < 6; i++) { color += letters[Math.floor(Math.random() * 16)]; } return color;
}
Explanation:
- This script listens for messages from the popup.
- When it receives a “changeColor” message, it changes the page’s background color to a random color.
- The getRandomColor() function generates a random hex color code.
Step 7: Load and Test the Extension
- Open Chrome and go to chrome://extensions/
- Enable “Developer mode” in the top right corner.
- Click “Load unpacked” and select your extension folder.
- Your extension should now appear in the Chrome toolbar.
- Open any webpage and click on your extension icon.
- Click the “Change Color” button and observe:
The webpage’s background color should change.
The count in the popup should increment.
Check the background script’s console (in the extensions page) for the log message.
Discover more from Coursity
Subscribe to get the latest posts sent to your email.