仅当匹配匹配时,Chrome扩展程序才会激活扩展

时间:2013-11-24 21:27:36

标签: google-chrome google-chrome-extension

我有background.js

的代码
function changeActive(tabId, changeInfo, tab){
     console.log(tab);
     chrome.pageAction.setPopup({
     "popup":"popup.html"
  });
   chrome.pageAction.setIcon({
   "path":"Facebook-icon16.png"
   });
  }
 chrome.tabs.onUpdated.addListener(changeActive);

我的清单有这个:

...  "content_scripts": [
{
  "matches": ["https://www.facebook.com/*"],
  "css": ["messenger.css"],
  "js":["messenger.js"],
  "run_at":"document_start"
}
 ],
  "version": "0.2",
 "permissions": [
      "activeTab","tabs"
      ]
   }

正如您所看到的,如果网址是Facebook,我正在尝试匹配,然后更改图标图像并显示弹出窗口。我也不希望他们能够点击图标,如果它不在Facebook标签上

1 个答案:

答案 0 :(得分:3)

由于您已经在使用内容脚本,因此最好使用 Message Passing ,以便通知后台页面它应该更改图标和弹出窗口。
E.g:

messenger.js

chrome.runtime.sendMessage({ onFacebook: true });

background.js

/* When the content scripts makes contact, 
 * set the page-action's icon and popup */
chrome.runtime.onMessage.addListener(function(msg, sender) {
    if (msg.onFacebook === true) {
        chrome.pageAction.setIcon({
            tabId: sender.tab.id,
            path: "path/to/active/icon.png"
        });
        chrome.pageAction.setPopup({
            tabId: sender.tab.id, 
            popup: "path/to/popup.html"
        });
    }
});

/* When the tab's address changes/reloads, 
 * clear the popup and reset the icon.
 * (If applicable, the newly injected content script will send a new message.) */
chrome.tabs.onUpdated.addListener(function(tabId, info, tab) {
    if (info.status === "loading") {
        chrome.pageAction.setIcon({
            tabId: tabId,
            path: "path/to/inactive/icon.png."
        });
        chrome.pageAction.setPopup({
            tabId: tabId, 
            popup: ""
        });
    }
});

另外,请注意: