Creating a Chrome Extension: A Comprehensive Guide

Sivaneni Prasanna
3 min readJul 2, 2024

--

Chrome extensions enhance the browsing experience by providing additional functionality to the browser. In this post, we’ll walk through the creation of a Chrome extension with several key components, providing code examples for each.

Overview of Basic Components

1. Manifest File (manifest.json)

The manifest file is the cornerstone of any Chrome extension, containing metadata about the extension, such as its name, version, permissions, and the scripts it uses.

{
"name": "Agoda OPENAI Chatbot",
"version": "0.1.0",
"description": "chat agent for agoda",
"default_locale": "en",
"permissions": [
"storage",
"tabs",
"background",
"scripting",
"activeTab",
"downloads",
"localStorage"
],
"host_permissions": [
"https://www.agoda.com/*",
"https://api.openai.com/v1/completions"
],
"background": {
"service_worker": "background.js"
},
"content_scripts": [
{
"matches": [
"https://*.agoda.com/*"
],
"js": [
"contentScript.js",
"extract.js"
]
}
],
"web_accessible_resources": [
{
"resources": [
"assets/bookmark.png",
"assets/play.png",
"assets/delete.png",
"assets/save.png",
"extract.js"
],
"matches": [
"https://*.agoda.com/*"
]
}
],
"action": {
"default_icon": {
"16": "assets/ext-icon.png",
"24": "assets/ext-icon.png",
"32": "assets/ext-icon.png"
},
"default_title": "agoda chatbot",
"default_popup": "popup.html"
},
"options_page": "options/options.html",
"manifest_version": 3
}

2. Content Script (contentScript.js)

Content scripts run in the context of web pages, allowing you to interact with the DOM of the pages the user visits.

// contentScript.js
document.addEventListener('DOMContentLoaded', () => {
const button = document.createElement('button');
button.textContent = 'Extract Content';
button.style.position = 'fixed';
button.style.top = '10px';
button.style.right = '10px';
button.style.zIndex = 1000;
document.body.appendChild(button);

button.addEventListener('click', () => {
const data = document.body.innerText;
chrome.runtime.sendMessage({ message: 'extract_data', data: data });
});
});

3. Background Script (background.js)

Background scripts are long-running scripts that manage the extension’s state and handle events. They facilitate communication between different parts of the extension.

// background.js
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.message === 'extract_data') {
console.log('Data extracted:', request.data);
chrome.storage.local.set({ extractedData: request.data }, () => {
console.log('Data stored in chrome.storage');
});
}
});

4. Popup Script (popup.js)

Popup scripts run in the context of the extension’s popup, allowing you to interact with the popup’s HTML and manage user interactions.

// popup.js
document.addEventListener('DOMContentLoaded', () => {
const displayDataButton = document.getElementById('displayData');
const dataContainer = document.getElementById('dataContainer');

displayDataButton.addEventListener('click', () => {
chrome.storage.local.get(['extractedData'], (result) => {
dataContainer.textContent = result.extractedData || 'No data extracted';
});
});
});

5. Popup HTML (popup.html)

The HTML file for the popup UI provides the structure and layout for the popup.

<!DOCTYPE html>
<html>
<head>
<title>Popup</title>
<script src="popup.js"></script>
</head>
<body>
<button id="displayData">Display Extracted Data</button>
<div id="dataContainer"></div>
</body>
</html>

6. Executing External Script (extract.js)

External scripts can be injected into web pages using the chrome.scripting.executeScript API.

// extract.js
(() => {
const data = document.body.innerText;
chrome.runtime.sendMessage({ message: 'extraction_done', data: data });
})();

7. Storing and Retrieving Data with chrome.storage

Chrome’s storage API allows you to store and retrieve data.

// Store data
chrome.storage.local.set({ key: 'value' }, () => {
console.log('Data is stored');
});
// Retrieve data
chrome.storage.local.get(['key'], (result) => {
console.log('Data retrieved:', result.key);
});

Complete Example Workflow

  1. Content Script: Adds a button to the webpage. When clicked, it extracts text data from the page and sends it to the background script.
  2. Background Script: Listens for messages from the content script, stores the extracted data in chrome.storage, and manages the extension's state.
  3. Popup: Provides a UI for the user to retrieve and display the extracted data.

Putting It All Together

Ensure you have the following files in your extension’s directory:

  • manifest.json
  • contentScript.js
  • background.js
  • popup.js
  • popup.html
  • extract.js (if you need to inject an external script)
  • Include any necessary icons in an icons folder.

With these files and this structure, you should have a basic working Chrome extension that demonstrates key features such as messaging between scripts, storing and retrieving data, and injecting scripts into web pages.

By following this guide, you can create a Chrome extension that interacts with web pages, manages state, and provides a user interface through popups. This foundational knowledge will help you build more complex and feature-rich extensions in the future.

--

--