span
span

Reputation: 5628

Display Firefox WebExtension Page Action when page loads

I have been trying to read up on how to use WebExtension Page Actions by reading the following docs:

I am unable to find how I configure my extension to show the page action button in the URL bar when a page from example.com has loaded. All the docs seem to assume the page action icon is already visible and shows how to handle clicks on it.

First I thought I could configure it through the manifest but it does not seem to be supported in the same way as content scripts. Then I tried to find an API to call from background.js but have not found any.

How do I show my page action icon on example.com?

Upvotes: 3

Views: 1148

Answers (2)

Starting with Firefox 59, there will be a much simpler solution. In manifest.json, just use the show_matches property of page_action:

"page_action": {
    "show_matches": ["*://*.example.com/*"],
    ...
}

Upvotes: 6

span
span

Reputation: 5628

Digging around the samples I found the following that listens for page loads across all tabs and updates the icon with popup that is configured in the manifest.

background.js

/*
Initialize the page action: set icon and title, then show.
Only operates on tabs whose URL's protocol is applicable.
*/
function initializePageAction(tab) {
  if (tab.url.includes("example.com")) {
    browser.pageAction.show(tab.id);
  }
}


/*
When first loaded, initialize the page action for all tabs.
*/
var gettingAllTabs = browser.tabs.query({});
gettingAllTabs.then((tabs) => {
  for (let tab of tabs) {
    initializePageAction(tab);
  }
});

/*
Each time a tab is updated, reset the page action for that tab.
*/
browser.tabs.onUpdated.addListener((id, changeInfo, tab) => {
  initializePageAction(tab);
});

manifest.json

"permissions": [
    "tabs",
    "activeTab"
  ],

  "content_scripts": [{
        "matches": ["*://*.example.com/*"],
        "js": ["content_scripts/download.js"]
      }
  ],

  "page_action": {
    "browser_style": true,
    "default_icon": {
      "19": "icons/download-19.png",
      "38": "icons/download-38.png"
    },
    "default_title": "Some title",
    "default_popup": "popup/popup.html"
  },

  "background": {
      "scripts": ["background.js"]
  }

Upvotes: 1

Related Questions