内容脚本是否可以访问新标签页?

Does content script have access to newtab page?

已更新

感谢@kofifus 提供的信息,Chrome 截至其默认新标签页上的 61 explicitly forbids 内容脚本

上一个

假设我有以下示例扩展,它将在控制台中输出 test

manifest.json

{
  "name": "Test",
  "version": "1.0",
  "manifest_version": 2,
  "content_scripts": [
    {
      "matches": [
        "<all_urls>"
      ],
      "js": [
        "content.js"
      ]
    }
  ]
}

content.js

console.log('test');

以上扩展在 chrome://newtab 页面中是否有效?

一些有用的信息:

  1. 我知道默认情况下 chrome 扩展无法访问 chrome:// 页面,我们可以通过 chrome://flags/#extensions-on-chrome-urls

  2. chrome://newtab其实和https://www.google.co.jp/_/chrome/newtab?espv=2&ie=UTF-8一样是url,所以不应该被上面的限制所屏蔽。

  3. 有许多可用的鼠标手势扩展,例如 crxMouse,它们在 chrome://newtab 页面上运行良好

  4. 也有一些声音说在chrome://newtab中不允许注入内容脚本,比如下面@Xan的评论this answer

所以它看起来很奇怪,因为它在不同设备(或设置?)上的行为不同。关于内容脚本是否可以在 chrome://newtab 页面中 运行 是否有任何官方声明?或者是否有我们可以更改此行为的设置?

Q: Is there any official statements about whether content scripts can run in chrome://newtab pages?

答:不是真的,但是 Google's documentation 指出:

Host permissions and content script matching are based on a set of URLs defined by match patterns. A match pattern is essentially a URL that begins with a permitted scheme (http, https, file, or ftp, and that can contain '*' characters. The special pattern matches any URL that starts with a permitted scheme.

chrome://newtab 只会将用户重定向到 url 设置为新标签页的任何内容。 通常它会将用户重定向到 https://<your local google domain>/_/chrome/newtab(允许的匹配模式)。但是,如果另一个扩展将新标签页设置为 customNewTab.html,则 chrome://newtab 会将用户重定向到 chrome-extension://chrome-id/customNewTab.html,并且任何其他扩展的内容脚本将无法 运行新标签页。

也证实了这一点。如果您尝试将 "exclude_matches": ["*://*/_/chrome/newtab*"], 添加到您的清单中,内容脚本将停止在新标签页上工作。

Q: Is there a setting that could change this behavior?

None 在另一个扩展设置的覆盖页面旁边。 (注意主题只会改变新标签的外观,不会覆盖新标签url)

Q: Will above extension work well in chrome://newtab page?

A:是的,除非该选项卡被另一个扩展覆盖。

我在扩展商店中有一个名为 Screen Shader 的 30,000 用户扩展,有多种不同的 chrome 版本和一些不同的浏览器,到目前为止,没有人抱怨它不能在新的上工作标签页,当他们抱怨很多其他事情时。

我不太清楚为什么其他人认为它不应该在新标签页上工作,但希望这能回答你的所有问题。

旁注:新标签页的按键问题

他在 http://www.toptip.ca/2010/01/google-chrome-content-script.html the developer of "Boss Key and Button" 的博文中抱怨 运行 在新标签页中使用内容脚本的问题。他的扩展程序将所有 chrome windows 最小化,并在您按 F9 时在新选项卡中打开您当前所在的那个。他认为内容脚本在新标签页上不起作用,因为每当他在新标签页中使用他的快捷方式时,什么也没有发生。他没有意识到它在新标签页上不起作用的原因是 chrome 将任何按键重定向到浏览器栏,因此他的内容脚本无法捕获按键。

尝试使用他的扩展程序并在随机页面上按 F9。所有 chrome windows 都将被最小化。返回那个随机页面,然后单击地址栏并尝试按 F9。这次不会有事了。

Chrome 截至其默认新标签页上的 61 explicitly forbids 内容脚本