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

Tampermonkey访问网站导航页面不加载脚本的解决方法咨询

问题解决思路

1. 定位问题根源

你的网站属于单页应用(SPA),这类网站通过前端路由(如Vue Router、React Router)跳转页面,不会触发浏览器的完整页面刷新。而Tampermonkey默认仅在页面首次加载(DOMContentLoaded/load事件触发时)执行脚本,因此通过主导航跳转时,脚本不会自动重新运行。

2. 修正脚本匹配规则

当前脚本的@match仅匹配根路径https://mywebsite.com/,如果导航跳转后的页面是子路径(如https://mywebsite.com/product/xxx),脚本根本不会被匹配到。需将匹配规则改为覆盖全站:

// @match        https://mywebsite.com/*

3. 监听页面路由变化(核心解决方案)

针对SPA的无刷新跳转,需要监听URL变化或页面内容更新事件,确保脚本在路由切换后重新执行,常用方案有三种:

方案一:监听History模式路由(popstate事件)

适用于使用HTML5 History API的SPA:

let lastUrl = window.location.href;
window.addEventListener('popstate', () => {
    if (window.location.href !== lastUrl) {
        lastUrl = window.location.href;
        productView();
    }
});

方案二:监听哈希模式路由(hashchange事件)

适用于用#标识路由的SPA:

window.addEventListener('hashchange', () => {
    productView();
});

方案三:监听DOM内容变化(兜底方案)

如果上述事件不生效,可通过MutationObserver监听页面内容更新,间接判断路由切换:

const observer = new MutationObserver(mutations => {
    const currentUrl = window.location.href;
    if (currentUrl !== lastUrl) {
        lastUrl = currentUrl;
        productView();
    }
});
observer.observe(document.body, { childList: true, subtree: true });

4. 优化脚本执行时机

避免在DOM未渲染完成时执行脚本,可添加延迟或等待DOM就绪:

function productView() {
    // 延迟100ms确保DOM元素加载完成
    setTimeout(() => {
        alert('1');
        // 这里编写针对当前页面的业务逻辑
        // 可通过window.location.pathname判断页面类型,避免无效执行
        if (window.location.pathname.includes('/product/')) {
            // 仅在商品页执行的逻辑
        }
    }, 100);
}

5. 检查Tampermonkey配置

确认Tampermonkey的「模式」设置为「正常」,未启用「仅在顶层文档」等限制选项,确保脚本能在动态加载的内容中正常运行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 22:15:55