Emilie
Emilie

Reputation: 35

How to run popup.html without using default_popup? (CHROME EXTENSION)

So, I've got a situation where I want a background and content script to be run everytime the browser extension icon is clicked. The ideal behaviour is that extension icon is clicked, the script runs, and the popup will open, displaying the data that was grabbed by the script (but this should happen quickly, the script runs and gets the data very fast). Since chrome.pageAction.onClicked will not work if there is a default_popup defined in manifest.json, I think this leaves me with two options:

  1. Use default_popup and figure out that the extension icon has been clicked some other way. I found this solution in another stack overflow post, but the workaround is to use default_popup: "popup.html", and then the popup.js that is defined in popup.html will send a message saying that the icon has been clicked, then when background.js receives this message, it executes the script. I implemented this idea and it worked... kinda. The trouble is, the popup will always come up before the script is fully executed, so you can't actually display the data grabbed by the script in the popup until the next click. I'm not sure there's any way to get the behaviour I desire using this method, so on to the next:
  2. The other solution I can possible think of is to use onClicked, and then make the popup come up some other way, besides using default_popup in manifest.json. I'm also not sure if this is possible, I have looked on stackoverflow and haven't found anything similar.

Is the second method possible? Can the first method work somehow?

Upvotes: 1

Views: 846

Answers (1)

cameck
cameck

Reputation: 2098

Your option #1 is correct, I think all that is needed is a loading screen when the user first sees the popup, and add some code that updates the popup as soon as it hears from the backend. Might need to see some code to better help there.

Option #2 will not really work, unless you opened the popup in a new tab (or just made it a whole new HTML page). I say this because there is a note here from the Chrome Dev team they will not support opening a popup unless it is from a user gesture -- https://stackoverflow.com/a/10484764/4875295.

If you wanted to go that route it would probably look something like:

  • Delete from your manifest.json browser_action.default_popup
  • In your background script add something like:
    chrome.browserAction.onClicked.addListener(() => {
        const data = dataMaker();
        chrome.tabs.create({
            url: `${chrome.runtime.getURL("app.html")}?data=${data}`
        });
    });
  • Then in your html file have some JS that reads the query string and updates the page accordingly.

Though, that's a different approach than you asked for and I think your original route may still be the best bet (with some added JS around loading).

Upvotes: 1

Related Questions