Chrome JavaScript API在各个地方使用match patterns。在Chrome扩展程序中,有没有办法手动调用Google用来测试URL是否遵循给定匹配模式的任何功能?我有一堆我想测试的网址。
答案 0 :(得分:3)
不,没有。但是,使用正则表达式复制并不困难。
这是一个实现。它检查匹配模式的正常限制,但不检查主机模式/测试URL主机的有效性。
function patternToRegExp(pattern){
if(pattern == "<all_urls>") return /^(?:http|https|file|ftp):\/\/.*/;
var split = /^(\*|http|https|file|ftp):\/\/(.*)$/.exec(pattern);
if(!split) throw Error("Invalid schema in " + pattern);
var schema = split[1];
var fullpath = split[2];
var split = /^([^\/]*)\/(.*)$/.exec(fullpath);
if(!split) throw Error("No path specified in " + pattern);
var host = split[1];
var path = split[2];
// File
if(schema == "file" && host != "")
throw Error("Non-empty host for file schema in " + pattern);
if(schema != "file" && host == "")
throw Error("No host specified in " + pattern);
if(!(/^(\*|\*\.[^*]+|[^*]*)$/.exec(host)))
throw Error("Illegal wildcard in host in " + pattern);
var reString = "^";
reString += (schema == "*") ? "https*" : schema;
reString += ":\\/\\/";
// Not overly concerned with intricacies
// of domain name restrictions and IDN
// as we're not testing domain validity
reString += host.replace(/\*\.?/, "[^\\/]*");
reString += "(:\\d+)?";
reString += "\\/";
reString += path.replace("*", ".*");
reString += "$";
return RegExp(reString);
}
// Usage example
// Precompile the expression for performance reasons
var re = patternToRegExp("*://*.example.com/*.css");
// Test against it
re.test("http://example.com/"); // false
re.test("https://example.com/css/example.css"); // true
re.test("http://www.example.com/test.css"); // true