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

如何检测SPA网站,避免Chrome扩展修改其HTML内容?

检测SPA(React/Vue/Angular)并跳过body修改的方法

可以通过以下几种方式组合检测SPA类型网站,避免在这类站点执行body修改操作:

1. 检测框架特有的全局变量或DOM标记

每个前端框架都会留下独特标识,可针对性检查:

React检测

  • 检查全局对象是否存在React或ReactDOM:
    const isReact = typeof window.React !== 'undefined' || typeof window.ReactDOM !== 'undefined';
    
  • 或检查DOM中是否存在React专属属性的元素:
    const isReact = document.querySelector('[data-reactroot], [data-reactid]') !== null;
    

Vue检测

  • 检查全局对象是否存在Vue或__VUE__:
    const isVue = typeof window.Vue !== 'undefined' || typeof window.__VUE__ !== 'undefined';
    
  • 或检查DOM中是否存在Vue的属性标记:
    const isVue = document.querySelector('[data-v-app], [data-v-]') !== null;
    

Angular检测

  • 检查全局对象是否存在angular或ng:
    const isAngular = typeof window.angular !== 'undefined' || typeof window.ng !== 'undefined';
    
  • 或检查DOM中是否存在Angular的ng-app属性:
    const isAngular = document.querySelector('[ng-app]') !== null;
    

2. 检测SPA路由特征

SPA通常使用客户端路由,可通过以下方式判断:

  • 检查地址栏是否存在hash路由(如#/path)或非根路径的HTML5 history模式:
    const isSPARoute = window.location.pathname !== '/' || window.location.hash !== '';
    
  • 或检查页面是否存在base标签(多数SPA会配置该标签):
    const hasBaseTag = document.querySelector('base[href]') !== null;
    

3. 组合检测逻辑,修改原有代码

将上述检测方式结合,提升判断准确性,最终代码示例:

document.addEventListener('DOMContentLoaded', () => {
    // 组合检测是否为SPA框架站点
    const isReact = typeof window.React !== 'undefined' || document.querySelector('[data-reactroot]') !== null;
    const isVue = typeof window.Vue !== 'undefined' || document.querySelector('[data-v-app]') !== null;
    const isAngular = typeof window.angular !== 'undefined' || document.querySelector('[ng-app]') !== null;
    const isSPA = isReact || isVue || isAngular;

    // 仅非SPA站点执行body修改
    if (!isSPA) {
        const body = document.body.innerHTML;    
        let body_edited = foo();
        document.body.innerHTML = body_edited;
    }
});

注意事项

  • 部分SPA会延迟加载框架全局变量,若出现漏判,可考虑通过setTimeout延迟检测,或监听DOMNodeInserted事件判断动态渲染内容。
  • 少数非SPA站点可能局部引入框架库,若需更精准判断,可结合路由特征与DOM结构(如是否仅存在单个根容器节点)综合校验。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 19:24:28