如何在Tampermonkey脚本中读取URL的查询参数?
如何在Tampermonkey脚本中读取URL查询参数
在Tampermonkey脚本里读取URL的查询参数,有两种简单可靠的方法:
方法一:使用原生URLSearchParams API(推荐)
这是现代浏览器支持的原生API,写法简洁直观:
// 获取当前页面的URL查询参数 const params = new URLSearchParams(window.location.search); // 读取arg1的值,如果不存在会返回null const arg1Value = params.get('arg1'); // 可以直接打印测试 console.log(arg1Value); // 输出"foo"
如果要检查某个参数是否存在,用has()方法:
if (params.has('arg1')) { // 存在arg1参数时的逻辑 }
方法二:正则匹配(兼容旧环境)
如果需要兼容非常老旧的浏览器,可以用正则表达式提取:
function getQueryParam(name) { const regex = new RegExp(`[?&]${name}=([^&]*)`); const match = window.location.search.match(regex); // 解码URL编码的字符,比如空格转%20的情况 return match ? decodeURIComponent(match[1]) : null; } // 使用示例 const arg1Value = getQueryParam('arg1'); console.log(arg1Value); // 输出"foo"
你的脚本@match规则已经覆盖了目标URL,只要脚本在对应页面正常运行,以上代码就能直接生效。
内容的提问来源于stack exchange,提问作者tenserudo
相关产品推荐
相关产品推荐

