You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

用户脚本替换故障:处理外链时当前URL被追加至结果前

问题分析与解决方案

问题原因

你遇到的核心问题是**jQuery.prop("href")返回的是浏览器解析后的绝对URL**,其中u参数的内容已经被URL编码(比如https://会被转成https%3A%2F%2F)。你的正则匹配的是未编码的原始字符串,导致替换后得到的是编码后的目标路径,浏览器会将这个非标准字符串视为相对路径,自动拼接到当前页面URL后,最终出现错误结果。

而你在控制台直接测试的是未编码的字符串,所以替换逻辑能正常生效。


解决方案

方案1:使用attr()获取原始href属性值

jQuery.attr("href")会返回a标签在HTML中定义的原始属性值(未经过浏览器编码解析),这样你的正则可以直接匹配目标字符串:

jQuery(document).on("mouseenter", "a", function(event) {
    const originalHref = jQuery(this).attr("href");
    // 增加判断避免重复处理
    if (originalHref?.includes("steamcommunity.com/linkfilter/?u=")) {
        const newHref = originalHref.replace(/https:\/\/steamcommunity\.com\/linkfilter\/\?u=/, "");
        jQuery(this).attr("href", newHref);
    }
});

方案2:处理编码后的URL(适配prop())

如果必须使用prop()获取解析后的完整URL,可以通过正则捕获u参数的值,再解码得到正确的目标URL:

jQuery(document).on("mouseenter", "a", function(event) {
    const fullHref = jQuery(this).prop("href");
    const linkFilterRegex = /https:\/\/steamcommunity\.com\/linkfilter\/\?u=(.*)/;
    const matchResult = fullHref.match(linkFilterRegex);
    
    if (matchResult) {
        // 解码URL编码的参数值
        const targetUrl = decodeURIComponent(matchResult[1]);
        jQuery(this).prop("href", targetUrl);
    }
});

优化建议:提前处理链接(避免重复触发)

mouseenter事件触发时机晚且可能重复执行,建议在页面加载完成后直接处理所有链接,并监听动态加载的内容:

jQuery(document).ready(function() {
    // 处理页面已存在的链接
    processLinks(jQuery("a"));

    // 监听动态新增的链接
    const observer = new MutationObserver(function(mutations) {
        mutations.forEach(mutation => {
            processLinks(jQuery(mutation.addedNodes).find("a"));
        });
    });
    observer.observe(document.body, { childList: true, subtree: true });
});

function processLinks($links) {
    $links.each(function() {
        const originalHref = jQuery(this).attr("href");
        if (originalHref?.includes("steamcommunity.com/linkfilter/?u=")) {
            jQuery(this).attr("href", originalHref.replace(/https:\/\/steamcommunity\.com\/linkfilter\/\?u=/, ""));
        }
    });
}

内容的提问来源于stack exchange,提问作者Dan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 03:17:11