简体   繁体   中英

What is the purpose of background.js on a chrome extension?

I don't see use for background.js or background.html just yet. It seems like just a middle man. I can easily communicate with all my content scripts by using the following code in popup.html/popup.js (browser action):

if (e.target.id === "blue"){
   chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
     var activeTab = tabs[0];
    chrome.tabs.sendMessage(activeTab.id, {"message": "blue" });
});
}

then on my content.js:

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {

 if( request.message === "blue" ) {
     document.body.style.backgroundColor="blue";
     console.log("Content: Changing to blue");
 }

 if( request.message === "black" ) {
     document.body.style.backgroundColor="black";
}

 });

PS Hope this helps someone out, I already have a working extension: :D

a file named background.js has no significance in chrome extensions, you must be asking about Background Pages or Event Pages

These pages do not have to have any particular name, they can be called fred.js or wilma.js - their "special purpose" is only realised if one adds them to the extension through the chrome extension manifest like so:

// background page
"background": {
  "scripts": ["fred.js"]
},
// event page
"background": {
  "scripts": ["wilma.js"],
  "persistent": false
},

The functionality offered by and use case for such pages is in the above linked documentation pages

From the docs

Extensions are event based programs used to modify or enhance the Chrome browsing experience. Events are browser triggers, such as navigating to a new page, removing a bookmark, or closing a tab. Extensions monitor these events in their background script , then react with specified instructions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM