Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between background pages and background scripts?

This article uses two terms "background page" and "background script"

I think of background script as of background field with scripts in Manifest.json

But what is the background page and how they differ?

like image 797
John Kent Avatar asked Dec 14 '22 15:12

John Kent


1 Answers

According to documentation:

The background script is the extension's event handler; it contains listeners for browser events that are important to the extension. It lies dormant until an event is fired then performs the instructed logic. An effective background script is only loaded when it is needed and unloaded when it goes idle.

You can configure if the background script remains dormant until needed or is always active with the persistentkey in the backgroundmanifest entry. For example:

"background": {
    "persistent": true,
    "scripts": ["myBackground.js"]
}

If you declare your background scripts using the scripts key (as above), Chrome will create an empty HTML page that includes the script(s) included in the script key of the background manifest entry. So in the case above, Chrome would create a background page like:

<html>
    <head>
    </head>
    <body>
        <script src="myBackground.js"></script>
    </body>
</html>

If you declare a background page instead, you decide what to include in the webpage, and you have to include your script tags in the page, since you cannot have both page and scripts keys in the background manifest entry.

The main difference (and advantage) of declaring a background page is that you can include whatever HTML elements you want in it. They will not be seen (background pages are never displayed), but they work as in any other webpage. For example, in the following background page I've included an audio tag to play music while the extension is running:

manifest.json

"background": {
    "persistent": true,
    "page": "myBackgroundPage.html"
}

myBackgroundPage.html

<html>
    <body>
        <audio id="mySong" src="mySong.mp3" autoplay loop></audio>
        <script src="myBackground.js"></script>
    </body>
</html>

You could have achieved the same result using only a script and including in it something like:

var myAudio = document.createElement('audio');
myAudio.src = 'mySong.mp3';
myAudio.autoplay = true;
myAudio.loop = true;
document.body.appendChild(myAudio);

but in cases like this I think that creating your own background page is more convenient.

like image 182
Iván Nokonoko Avatar answered May 25 '23 17:05

Iván Nokonoko