如何检测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
相关产品推荐
相关产品推荐

