在页面加载时显示Firefox WebExtension页面操作

时间:2017-09-24 09:24:28

标签: firefox-webextensions

我一直试图通过阅读以下文档来了解如何使用WebExtension页面操作:

我无法找到如何配置我的扩展程序,以便在加载example.com的页面时在网址栏中显示网页操作按钮。所有文档似乎都认为页面操作图标已经可见,并显示了如何处理它的点击。

首先,我认为我可以通过清单配置它,但似乎不像内容脚本那样支持它。然后我尝试从background.js找到要调用的API,但没有找到任何API。

如何在example.com上显示我的页面操作图标?

2 个答案:

答案 0 :(得分:3)

Firefox 59开始,将会有一个更简单的解决方案。在manifest.json中,只需使用page_action的 show_matches 属性:

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

答案 1 :(得分:1)

挖掘the samples我发现以下内容会侦听所有选项卡中的页面加载,并使用清单中配置的弹出窗口更新图标。

<强> 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"]
  }
相关问题