我正在尝试创建一个Chrome扩展程序,以便在测试特定网站时将主机/域更改通知我。通常会出现指向开发人员或实际环境的链接,如果我遵循这些链接之一,我会被警告,因为这些网站通常是相同的。
为清楚起见,请进行编辑:当链接使我离开http(s://://example.staging.something.com)并进入实时网站http(s)://www.example.com时,我希望它提醒我或开发网站http(s)://example.dev.something.com
到目前为止,我已经成功创建了一个脚本,该脚本可以标识何时使用暂存URL(我们的测试环境),但是当我导航到不包含“分期”。
我的manifest.json
{
"manifest_version": 2,
"name": "A What URL",
"description": "This extension monitors and warns you of domain changes",
"version": "1.0",
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"background": { "scripts": ["background.js"],
"persistent": false
},
"permissions": [
"activeTab",
"webNavigation"
]
}
我的background.js
chrome.webNavigation.onCommitted.addListener(function(e) {
alert ("you are still on staging!");
}, {url: [{hostContains: 'staging'}]});
我敢肯定这很简单,但看来我的大脑要简单得多!
最佳答案
不幸的是,您不能“反转”过滤器,因此必须捕获所有事件并在代码中过滤。
Chrome活动来了。您的代码建议您将它们像DOM事件一样对待(使用e
参数)。取而代之的是,它们根据所涉及的事件传递参数,有时是几个。
如果查看the documentation,则会看到预期的回调格式为:
function(object details) {...};
其中,
details
将包含url
属性。因此,您将拥有:
chrome.webNavigation.onCommitted.addListener(function(details) {
// Regexp matches first "//", followed by any number of non-/, followed by "staging"
if(!details.url.match(/[^\/]*\/\/[^\/]*staging/)) {
alert ("This is no longer staging!");
}
});
请注意,除非您将其关闭,否则这将非常烦人-毕竟它将与几乎所有页面匹配。