【问题标题】:Chrome Extension content scripts not firing codeChrome 扩展内容脚本不触发代码
【发布时间】:2015-11-28 04:08:33
【问题描述】:

我正在尝试获取用户访问的每个新页面的 URL。我找到了一个说使用content_scripts 的答案,所以我把它放在我的清单中:

"permissions": [
  "tabs"
],
"content_scripts": [
{
  "matches": ["<all_urls>"],
  "js": ["js/background.js"]
}

我也尝试过这样的匹配:

"matches": ["http://*/*", "https://*/*"],

这是我的background.js 文件:

chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
    alert(changeInfo.url);
});

chrome.tabs.onActivated.addListener(function(activeInfo) {
  // how to fetch tab url using activeInfo.tabid
  chrome.tabs.get(activeInfo.tabId, function(tab){
     console.log(tab.url);
  });
});

alert("BACON");

重新加载扩展程序然后打开新标签并访问各种网站后,什么都不会被触发。有人可以帮我弄清楚我做错了什么吗?谢谢!

【问题讨论】:

标签: javascript google-chrome google-chrome-extension


【解决方案1】:

根据content scripts documentation

内容脚本有一些限制。他们不能使用 chrome.* API,但以下情况除外:

  • 扩展(getURL、inIncognitoContext、lastError、onRequest、sendRequest)
  • i18n
  • 运行时(连接、getManifest、getURL、id、onConnect、onMessage、sendMessage)
  • 存储

解决方案:为了访问chrome.tabs API,您应该使用后台页面脚本。

还要注意根据chrome.tabs API documentation

您可以使用大多数 chrome.tabs 方法和事件,而无需在扩展的清单文件中声明任何权限。但是,如果您需要访问 tabs.Tab 的 url、title 或 favIconUrl 属性,则必须在清单中声明 "tabs" 权限

ma​​nifest.json

...
"permissions": [
  "tabs"
],
"background": {
  "scripts": ["background.js"]
},
...

background.js

chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
  if (changeInfo.status==='loading' && changeInfo.url) {
    alert(changeInfo.url);
  }
});

【讨论】:

  • 另外,为了进一步说明,我已经在清单中获得了“标签”权限。解决问题的原因实际上是没有使用 content_script。在清单中声明后台脚本实际上是解决问题的方法。
  • @Sloganho,确实,我在问题中错过了这一点。您可能想阅读extension architecture overview(可以说大约有一半的问题是因为人们没有阅读它而被问到的)。
猜你喜欢
  • 1970-01-01
  • 2012-04-12
  • 2016-07-10
  • 1970-01-01
  • 1970-01-01
  • 2015-12-24
  • 2016-12-23
  • 2011-09-28
  • 1970-01-01
相关资源
最近更新 更多