๐ ๏ธ How to Create a Service Worker for Chrome Extensions
Service workers are a key component of modern Chrome extensions, replacing the older background scripts. This guide will walk you through creating and implementing one in your extension.
๐ What is a Service Worker?
A service worker in a Chrome extension is a background script that:
- Runs separately from web pages
- Handles events (like install, messages, etc.)
- Is short-lived and event-based
- Has no access to the DOM or
window
object
๐ฆ Steps to Create a Service Worker
1. Create the Service Worker File
Create a new file in your extension directory named background.js
.
2. Write Your Service Worker Script
chrome.runtime.onInstalled.addListener(() => {
console.log('Extension installed');
});
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.action === 'performTask') {
// Perform some task
sendResponse({result: 'Task completed'});
}
return true;
});
This script listens for install and message events.
3. Register the Service Worker in manifest.json
{
"manifest_version": 3,
"name": "My Extension",
"version": "1.0",
"description": "An extension with a service worker",
"background": {
"service_worker": "background.js"
}
}
๐งฉ Using the Service Worker
You can send messages to the service worker like this:
chrome.runtime.sendMessage({action: 'performTask'}, response => {
console.log(response.result); // "Task completed"
});
โ Best Practices for Service Workers
- Keep them lightweight โ avoid unnecessary complexity
- Use event listeners โ structure code around event-based architecture
- No DOM access โ service workers can't access the DOM or
window
- Persist data โ use
chrome.storage
to store state between restarts - Handle errors gracefully โ service workers can be terminated anytime
๐ Common Use Cases
- Listening for browser events (tab updates, alarms, bookmarks)
- Managing extension-wide state
- Handling background API requests
- Running periodic tasks using
chrome.alarms
๐งช Debugging Service Workers
- Use
console.log()
in your worker - Go to
chrome://extensions
โ Click "Service Worker" under your extension - Use DevTools to inspect the worker
๐ Making API Calls from Service Workers
Service workers are ideal for network requests and background API interactions. Learn more in our API call guide for Chrome extensions.
๐งพ Conclusion
Service workers offer a modern, efficient way to handle background logic in Chrome extensions. Compared to legacy background scripts, they provide a more scalable, event-driven architecture.
Take time to experiment, test thoroughly, and structure your logic to align with how service workers operate.
Happy building from the Mellowtel Team! ๐