【问题标题】:Chrome userscript fires on all pages despite @match and @include settings尽管有 @match 和 @include 设置,Chrome 用户脚本仍会在所有页面上触发
【发布时间】:2013-04-30 11:16:40
【问题描述】:

我使用 match 来限制我的脚本只能在一个域中运行,但 chrome 会在每个域中运行它。我尝试了@include@match,当我尝试安装它并在所有网站上运行它时,它显示“访问所有网站上的数据”。

如何在 chrome 中将用户脚本限制为一个域?

元数据与本页相同:http://www.chromium.org/developers/design-documents/user-scripts

我的意思是:

// @match http://*.google.com/*
// @match http://www.google.com/*

【问题讨论】:

  • 您是要安装 zip / crx 文件还是 .user.js 文件?
  • 我说的是用户脚本,所以它是 .user.js
  • Chrome 将用户脚本转换为原生 Chrome 扩展,其匹配模式等同于 <all_urls>,然后通过 "include_globs" 限制页面。不用担心警告,它会按照您的预期运行。如果你想得到一个不那么可怕的警告,你需要从你的用户脚本创建一个 Chrome 扩展,并编辑 manifest.json 文件的“content_scripts”部分。有关从用户脚本生成 Chrome 扩展程序的步骤,请参阅 this answer
  • 您链接的示例包含http://*/*。显然,这将在所有页面上运行。我还检查了自动生成的manifest.json,它包含预期值。阅读stackoverflow.com/a/11773654/938089 以了解如何获取和查找自动生成的manifest.json 文件。编辑:删除 // @matches http://*/* 后,代码仅在 Google 上运行 - 正如预期的那样。
  • 请发布解决方案的答案(并删除一些可能对未来读者无用的 cmets)。其他人可能会从您的发现中受益。

标签: javascript google-chrome userscripts


【解决方案1】:

注意:这个答案是在 OP 和 Rob W 之间开发的。放置它 在这里希望这个问题可能对其他人有用 必须筛选上面的评论链。


有两个问题。首先,a userscript header does not parse if a UTF8 BOM is present(Chromium 错误 102667)。

其次,当在用户脚本中使用@include@match 时,Chrome 会误导性地报告该脚本可以“访问所有网站上的数据”,但事实并非如此。该脚本将仅在包含语句指定的那些站点上运行。

考虑(或制作)这三个脚本:

UTF 测试,不是 UTF.user.js(使用 ANSI 编码保存):

// ==UserScript==
// @name    Not UTF source file
// @match   http://www.yahoo.com/*
// ==/UserScript==
if (location.hostname != 'www.yahoo.com')
  alert ("This script should not run on "+location.hostname+"!");


UTF 测试,是 UTF.user.js(使用 UTF-8 编码保存,包括 BOM):

// ==UserScript==
// @name    Is UTF source file
// @match   http://www.yahoo.com/*
// ==/UserScript==
if (location.hostname != 'www.yahoo.com')
  alert ("This script should not run on "+location.hostname+"!");


包含,不匹配.user.js(使用 ANSI 编码保存):

// ==UserScript==
// @name    Use include, not match
// @include http://www.yahoo.com/*
// ==/UserScript==
if (location.hostname != 'www.yahoo.com')
  alert ("This script should not run on "+location.hostname+"!");


请注意,所有 3 个脚本都是相同的代码。只有@name 和/或文件格式和/或@include@match 不同。


带有匹配项的 ANSI 脚本(UTF 测试,而不是 UTF.user.js)报告这些权限:


此脚本按预期正确运行和报告。


带有匹配项的 UTF-8 脚本(UTF 测试,是 UTF.user.js)报告以下权限:


权限报告不正确,与@match 语句相矛盾。另请注意,显示的文件名是 URL 编码的,而不是 @name 指令。这些都是有问题的线索。

更糟糕的是,此脚本将在所有网站上运行。也就是说,您将在所有非雅虎页面上看到 alert()。这显然是a bug


带有 include (Include, not match.user.js) 的 ANSI 脚本报告这些权限:


虽然这是一个误导性的报告,但该脚本实际上会正确运行。也就是说,它只会触发 yahoo 页面。

这部分是由于 Chrome 如何将用户脚本自动转换为扩展程序。 @match 语句直接转换为manifest.jsonmatches 属性,而@include 语句转换为include_globs 值。见Match patterns and globs。 权限报告键来自matches 数组。

【讨论】:

    猜你喜欢
    • 2015-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多