尽管有@match和@include设置,但所有网页上的Chrome用户都会触发

Lea*_*dri 6 javascript google-chrome userscripts

我使用match来限制我的脚本只能使用一个域,但chrome会在每个域中运行它.我试着@include@match它说:"访问的所有网站上的数据"当我尝试安装它,它运行它的所有网站.

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

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

我的意思是:

// @match http://*.google.com/*
// @match http://www.google.com/*
Run Code Online (Sandbox Code Playgroud)

Bro*_*ams 7

注意:这个答案在OP和Rob W之间形成.希望这个问题可能对其他人有用,而不必筛选上面的评论链.


有两个问题.首先,如果存在UTF8 BOM,则不会解析userscript标头(Chromium bug 102667).

二,使用时@include@match在userscript,Chrome的误导性报道,该脚本可以"在所有网站上访问你的数据",但这不是真的.该脚本仅在include语句指定的站点上运行.

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

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+"!");
Run Code Online (Sandbox Code Playgroud)


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+"!");
Run Code Online (Sandbox Code Playgroud)


包含,不匹配.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+"!");
Run Code Online (Sandbox Code Playgroud)


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


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

ANSI加匹配
此脚本按预期正确运行和报告.


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

UTF加匹配
权限报告不正确,与@match语句相矛盾.另请注意,文件名显示为URL编码,而不是@name指令.这些都是有些不对劲的线索.

更糟糕的是,此脚本将在所有站点上运行. 也就是说,您将alert()在所有非Yahoo页面上看到.这显然是一个错误.


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

ANSI plus包括
虽然这是一个误导性的报告,但该脚本实际上会正常运行.也就是说,它只会触发雅虎页面.

这部分是由于Chrome如何将用户脚本自动转换为扩展程序. @match声明直接翻译成manifest.jsonmatches财产,而@include语句做成include_globs值.请参阅匹配模式和globs.权限报告关闭matches数组.