4 Understanding Chrome Extensions Background Scripts

Simply put background scripts are service workers JavaScript files that handle the extensions main events. They operate independent of a webpage and/or the extension popup.

Setting Up Background Scripts

Here is code on how you declare a background script in the manifest.json file.

{
...
"background": {
"service_worker": "background.js",
"type": "module"
},
...
}

The JavaScript file background.js can be named anything and be placed into any folder/directories just make sure that it the path should relative to the manifest.json file location.

{
...
"background": {
"service_worker": "./background/my-background-script.js",
"type": "module"
},
...
}

Use Cases of Background Scripts

Although background scripts are not mandatory to have in our extensions, they proof to be very useful. You can run code when important event occur in our extensions for instance;

When a User Installs the extension


chrome.runtime.onInstalled.addListener(function (details) {

const INSTALL = "install", UPDATE = "update", CHROME_UPDATE = "chrome_update", SHARED_UPDATE = "shared_module_update";

if (details.reason === INSTALL) {
// Do something here.
}

if (details.reason === UPDATE || details.reason === CHROME_UPDATE || details.reason === SHARED_UPDATE) {
// Do something here.
}

});

When the browser has just been open for the first time.

chrome.runtime.onStartup.addListener(() => {
// maybe open your favourite youtube channel
});

Receive/Send Messages for/to Content Scripts

We look at communication between background and content scripts more deeply in a the next article.

chrome.runtime.onMessage.addListener((request, sender, sendResponse)=>{ 
//request - data coming from the content
//sender - info about the sender
//sendResponse - a callback function to send data back to where its coming from.

if (request.myIdExists){
// do something
sendResponse(true);
}


sendResponse(false);
return true;
});

When one of the tabs has been updated

chrome.tabs.onUpdated.addListener(async function (tabId, changeInfo, tab) {
console.log(tabId, changeInfo, tab);
});

And so much more… You get the point. It’s a good place to do call APIs and other background tasks especially when the data is needed prior to a webpage or extension popup opening.

Unlike content scripts, background scripts can use all the chrome extension APIs; alarms, storage, runtime, contextMenu and many more.

Background Scripts and the DOM

Photo by Ben Kolde on Unsplash

Unlike content scripts, background scripts do not have access to the DOM, so code like

document.querySelectorAll('h2'); 
document.getElementId('that-element');
document.body.style.background = "gold";

does not work

Can I have multiple background scripts in my chrome extension?

Well the answer to this question is yes and no. You’ll notice that in the manifest.json file declared above, the service_worker is just defined by one file. Manifest Version 3 does not allow you to include multiple background service worker scripts in your manifest.json file.

However there is a work around. By using the importScripts function in main background script file, you can include the code from other files saved elsewhere in your project.

importScripts('./folder/extra-background-script.js');

There are a lot of interesting things you can do with background scripts we hope the open the world of chrome extensions and its possibilities.

Leave a Reply

Your email address will not be published. Required fields are marked *

More Articles & Posts