Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to have background script and something similar to a default popup?

So, I understand that you cannot have background scripts and a default popup together. If this is so, how can I have something similar to a default popup (where there is some simple HTML that appears when you clicked the extension's icon) and have the background script modify the contents of that popup?

Here's the manifest.json

"browser_action": {
    "default_title": "Mark this position!",
    "default_icon": "icon.png"
},
"background": {
    "scripts": ["background.js"],
    "persistent": false
},
"content_scripts": [
    {
        "matches": [
            "http://*/*",
            "https://*/*"
        ],
        "js": ["content.js"]
    }
],
like image 949
Farhad Ghayour Avatar asked Dec 13 '25 23:12

Farhad Ghayour


1 Answers

You absolutely can have both a popup (i.e. default_popup set) and a background page. The background page will have its own lifecycle (with "persistent": false it's an Event page) and the popup will exist as long as it's open.

I guess your confusion stems from the fact that you cannot have a popup and a chrome.browserAction.onClicked listener at the same time.

This is true, but there are other ways to tell your background page that the popup has opened.

You can message the background page from the popup:

// popup.js, should be included in the popup
chrome.runtime.sendMessage({popupOpen: true}, function(response) {
  /* process response */
});

// background.js
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
  if(message.popupOpen) {
    /* do stuff */
    sendResponse(response);
  }
});

If you put the above popup code on the top level, then the background will be informed as soon as the popup opens.

While you can directly access the popup's window from the background (see chrome.extension.getViews), it's recommended that you move the UI logic into the popup itself and communicate with the background using Messaging as above and shared chrome.storage.

like image 115
Xan Avatar answered Dec 15 '25 11:12

Xan