Skip to content Skip to sidebar Skip to footer

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 simpl

Solution 1:

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.


Post a Comment for "How To Have Background Script And Something Similar To A Default Popup?"