关键信息
GM_info.script.matches
: 会返回一个数据,其中按顺序列出了当前脚本定义的所有 @match
示例
// ==UserScript==
// @name TEST测试专用
// @namespace http://www.jerry.com/
// @version 0.1
// @author jerryjin
// @icon https://g.csdnimg.cn/static/logo/favicon32.ico
// @match *://*.csdn.net/*
// @match *://*.baidu.com/*
// @match *://*.toutiao.com/*
// @match *://*.bilibili.com/*
// ==/UserScript==
(async function() {
'use strict';
console.log('-------------------------- TEST测试专用 --------------------------');
var strategys = {
fn1:function(){console.log('策略A')},
fn2:function(){console.log('策略B')},
fn3:function(){console.log('策略C')}
};
// 根据当前匹配的页面,获取处理策略
var strategy = {
"0" : strategys.fn1,
"1" : strategys.fn2,
"2" : strategys.fn3,
"3" : strategys.fn3,
}[GM_info.script.matches
.map(rule =>rule.replace(/\.|\*|\/|\?/g, match=>({".":"\\.", "*":".*", "/":"\\/", "?":"\\?"}[match])))
.map(rule =>new RegExp(rule))
.map((regExp, index) => regExp.test(window.location.href) ? index : null)
.filter(index => index != null ).join()];
strategy(); // 执行策略
})();