How to create Chrome extension using JavaScript?
How to create Chrome extension using JavaScript?
25620-Jul-2023
Updated on 21-Jul-2023
Home / DeveloperSection / Forums / How to create Chrome extension using JavaScript?
How to create Chrome extension using JavaScript?
Aryan Kumar
21-Jul-2023To create a Chrome extension using JavaScript, you will need to create a manifest file, a content script, and a background script.
1. Create a manifest file
The manifest file is a JSON file that contains the metadata for your extension. It includes the name, version, description, and permissions that your extension needs.
To create a manifest file, open a text editor and create a file called
manifest.json
. Then, paste the following code into the file:2. Create a content script
The content script is a JavaScript file that runs in the context of the web pages that your extension is installed on. It can be used to modify the DOM, inject JavaScript, or listen for events.
To create a content script, open a text editor and create a file called
contentscript.js
. Then, paste the following code into the file:This code listens for the
chrome.tabs.onUpdated
event. When this event is fired, the code checks to see if the tab has finished loading. If the tab has finished loading, the code then finds the element with the classmy-element
and sets its text content to "Hello, world!".3. Create a background script
The background script is a JavaScript file that runs in the background of the browser. It can be used to perform tasks that do not need to be tied to a specific web page, such as storing data or communicating with a web server.
To create a background script, open a text editor and create a file called
background.js
. Then, paste the following code into the file:This code gets the value of the
myData
key from the browser's storage. If themyData
key does not exist, the code sets the value of the key to "Hello, world!". The code then sets the value of themyData
key in the browser's storage.The code also listens for the
chrome.tabs.onActivated
event. When this event is fired, the code sends a message to the tab with the idtab.id
. The message contains the text "Hello, world!".Once you have created the manifest file, the content script, and the background script, you can package your extension into a .crx file using the Chrome Extension Developer Tools.
To package your extension, open the Chrome Extension Developer Tools and click on the "Pack extension" button. In the "Package extension" dialog box, select the manifest file, the content script, and the background script. Then, click on the "Pack" button.
Once your extension has been packaged, you can install it in Chrome by dragging the .crx file to the Chrome toolbar.