Chrome 扩展程序仅在单击某些网页时起作用

2023-11-30

我正在尝试让我的 Chrome 扩展程序在用户打开时弹出警报http://google.com/并单击扩展图标。

我有以下清单:

{
   "manifest_version": 2,

   "name":  "One Megahurt",
   "version": "0.1",

   "permissions": [
       "activeTab"
    ],

   "background": {
       "scripts": ["bg.js"],
       "persistent": false
    },

    "browser_action": {
        "default_icon": "icon.png"
    } 
}

这是 bg.js:

chrome.browserAction.onClicked.addListener(function(tab) {
     alert('Test!');
})

此代码将允许在任何网站上弹出警报,因为我对其适用于哪些网站没有任何限制。我尝试使用

if(tab.url === "https://google.com/")

在第一行和第二行之间,但这不起作用。

我不确定我是否应该使用后台脚本而不是内容脚本。我查看了 Google 的示例并尝试使用“按 URL 进行页面操作”中的实现,但这对我来说也不起作用。

任何帮助,将不胜感激。我应该指出,我并不真正关心 URL 的具体问题——google.com 只是一个例子。我想学习将其用于其他项目和网站。

编辑:向权限添加 url 也不会限制警报弹出的网站。


根据菲利克斯·金的建议,我最终使用页面操作作为我的解决方案。回想起来,这是最好的解决方案,因为它不会在每个页面上加载扩展并导致浏览器速度变慢(据我所知)。

除了将域添加到清单中的权限之外,还将以下代码添加到background.js.

// When the extension is installed or upgraded ...
chrome.runtime.onInstalled.addListener(function() {
  // Replace all rules ...
  chrome.declarativeContent.onPageChanged.removeRules(undefined, function() {
    // With a new rule ...
    chrome.declarativeContent.onPageChanged.addRules([
      {
        // That fires when a page's URL matches one of the following ...
        conditions: [
          new chrome.declarativeContent.PageStateMatcher({
            pageUrl: { urlMatches: 'http://google.com/' }, // use https if necessary or add another line to match for both
          }),
          new chrome.declarativeContent.PageStateMatcher({
            pageUrl: { urlMatches: 'http://facebook.com/*' },
          }) // continue with more urls if needed
        ],
        // And shows the extension's page action.
        actions: [ new chrome.declarativeContent.ShowPageAction()]
      }
    ]);
  });
});

chrome.pageAction.onClicked.addListener(function(tab) {
    chrome.tabs.executeScript(null, { file: "script.js" });
});

需要添加的关键部分manifest.js are:

"background": {
  "scripts": ["res/background.js"],
  "persistent": false
}

&

"permissions": [
        "declarativeContent", "tabs", "activeTab", "http://google.com", "http://facebook.com/*"
    ]
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Chrome 扩展程序仅在单击某些网页时起作用 的相关文章

随机推荐