如何用Greasemonkey/Tampermonkey改写指定域名下的按钮URL链接?
Tampermonkey脚本实现按钮链接替换
直接上可运行的脚本,你可以根据需求修改开头的配置变量:
// ==UserScript== // @name 按钮链接清理替换 // @namespace http://tampermonkey.net/ // @version 0.1 // @description 替换指定域名下按钮链接,移除查询参数并替换前缀 // @match *://127.0.0.1:6878/* // 替换成你的目标域名,比如 *://mydomain.com/* // @match *://mydomain.com/* // 可添加多个匹配域名 // @grant none // ==/UserScript== (function() { 'use strict'; // 配置区:根据你的需求修改以下变量 const STRING_1 = 'http://127.0.0.1:6878/webui/player'; // 原链接前缀 const REPLACEMENT_1 = 'https://your-new-domain.com/new-path'; // 替换后的前缀 // 获取所有按钮类元素(含原生按钮和按钮样式的链接) const buttonElements = document.querySelectorAll('button, a[role="button"], .button'); buttonElements.forEach(elem => { // 处理href属性的链接 if (elem.href) { const url = new URL(elem.href); // 移除?及后面的查询参数 const urlWithoutSearch = `${url.origin}${url.pathname}`; // 替换前缀 if (urlWithoutSearch.startsWith(STRING_1)) { const newLink = urlWithoutSearch.replace(STRING_1, REPLACEMENT_1); elem.href = newLink; } } // 处理onclick中的链接(如果存在) const onclickAttr = elem.getAttribute('onclick'); if (onclickAttr) { const linkMatch = onclickAttr.match(/window\.open\(['"](.*?)['"]/); if (linkMatch) { const urlStr = linkMatch[1]; const url = new URL(urlStr); const urlWithoutSearch = `${url.origin}${url.pathname}`; if (urlWithoutSearch.startsWith(STRING_1)) { const newLink = urlWithoutSearch.replace(STRING_1, REPLACEMENT_1); elem.setAttribute('onclick', onclickAttr.replace(urlStr, newLink)); } } } }); })();
关键部分说明:
- 域名匹配:修改
@match后的地址,比如要匹配mydomain.com全量页面,就写*://mydomain.com/*,可多写几行覆盖不同域名。 - 链接处理:用
URL对象解析链接比正则更稳妥,自动拆分域名、路径和查询参数,先移除?及后续内容,再替换指定前缀。 - 元素覆盖:除了原生
<button>,还包含带按钮属性/样式的<a>标签,确保覆盖大多数页面按钮场景。
补充提示:
如果页面按钮是动态加载的(比如滚动后才出现),需要加DOM变化监听逻辑,可留言我补充这部分代码。
内容的提问来源于stack exchange,提问作者Jose Hidalgo
相关产品推荐
相关产品推荐

