在 Backround.js Chrome 扩展中使用匹配模式

Using Match Patterns In Backround.js Chrome Extension

我正在做一个 chrome 扩展项目,但无法使匹配模式起作用,因此它涵盖了用户经过该域的所有地方。例如,如果用户转到 https://www.google.com/imghp?hl=en 让代码在那里再次执行。这可以在 background.js 文件中完成吗?

  chrome.webNavigation.onCompleted.addListener(function() {
      alert("This is my favorite website!");
  }, {url: [{urlMatches : '*://www.google.com/*'}]});

我试过为“://www.google.com/”使用变量,例如:

var site = "*://www.google.com/*"
will not let me pass this into either url: 'site'
or {url: [{urlMatches : 'site'}

正如您在 documentation urlMatches doesn't use match patterns, it uses regular expressions with RE2 syntax 中看到的那样。

对于 *://www.google.com/* 你可以简单地切换到 hostEquals:

chrome.webNavigation.onCompleted.addListener(info => {
  console.log(info);
}, {
  url: [{hostEquals: 'www.google.com'}],
});

请注意 JavaScript 中的 'site' 是与变量 site 无关的文字字符串。