Creating an extension for a browser like Google Chrome or Microsoft Edge is a process that can be broken down into a few steps. Here is the basic procedure:
1. Configuring the extension folder and manifest file
Create a new folder on your computer where you will store all the files related to the extension. You can name it something like "MyFirstExtension".
Add the file
manifest.json
to this folder. The manifest file contains metadata about the extension, such as name, version, description, and required permissions. Sample code for the filemanifest.json
looks like this:{ "manifest_version": 3, "name": "My First Chrome Extension", "version": "1.0", "description": "A simple Chrome extension tutorial", "icons": { "48": "icon.png" }, "permissions": ["tabs", "activeTab", "scripting"], "action": { "default_icon": "icon.png", "default_popup": "popup.html" }, "background": { "service_worker": "background.js" }, "content_scripts": [ { "matches": ["https://*/*"], "js": ["content.js"] } ] }
permissions -
What permissions should I declare when creating a browser extension manifest?action -
background -
content_scripts -
2. Creating an icon and a popup
Create an icon for your extension. It can be a 48x48 pixel PNG file, named
icon.png
.Create an HTML file called
popup.html
, which will contain the content of the popup. Sample code forpopup.html
:<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>My First Extension</title> <style> body { font-family: Arial, sans-serif; margin: 10px; } </style> </head> <body> <h1>Hello, world!</h1> <p>This is a simple Chrome extension tutorial.</p> <button id="changeColor">Change background color</button> <script src="popup.js"></script> </body> </html>
3. Writing scripts background.js
and content.js
Create a file
background.js
that will contain the background logic. Sample code:chrome.action.onClicked.addListener((tab) => { chrome.scripting.executeScript({ target: { tabId: tab.id }, files: ['content.js'] }); });
Create a file
content.js
that will contain scripts that run on web pages. Sample code:document.body.style.backgroundColor = 'yellow';
4. Creating the popup.js executable file
document.addEventListener('DOMContentLoaded', function()
{
let changeColorButton = document.getElementById('changeColor');
changeColorButton.addEventListener('click', function()
{
chrome.tabs.query({active: true, currentWindow: true}, function(tabs)
{
chrome.scripting.executeScript(
{
target:
{
tabId: tabs[0].id
},
function: changeBackgroundColor
});
});
5. Testing the extension
- Open Chrome and go to
chrome://extensions
. - Turn on developer mode in the upper right corner.
- Click "Load Unpacked" and select the folder with the extension.
- Check if the extension works by clicking on its icon in your browser .
Comments
Post a Comment