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

Manifest 3 Chrome扩展实现特定链接始终重定向的方法

解决Manifest V3扩展中Instagram SPA路由跳转不触发重定向的问题

问题原因

Instagram是单页应用(SPA),点击reels按钮时通过前端路由(history.pushState/replaceState)更新URL,不会发起新的主框架网络请求。你当前的declarativeNetRequest规则仅拦截主框架的HTTP请求,因此这种前端路由跳转场景不会触发重定向。

解决方案

需要结合声明式网络请求规则和内容脚本监听路由变化,覆盖直接访问和SPA跳转两种场景:

1. 优化declarativeNetRequest规则

修改rules1.json,覆盖/reels和/reels/*两种路径,并提高优先级确保规则生效:

[
  {
    "id": 1,
    "priority": 10,
    "action": {
      "type": "redirect",
      "redirect": {
        "url": "https://www.instagram.com"
      }
    },
    "condition": {
      "urlFilter": "https://www.instagram.com/reels",
      "resourceTypes": ["main_frame"]
    }
  },
  {
    "id": 2,
    "priority": 10,
    "action": {
      "type": "redirect",
      "redirect": {
        "url": "https://www.instagram.com"
      }
    },
    "condition": {
      "urlFilter": "https://www.instagram.com/reels/*",
      "resourceTypes": ["main_frame"]
    }
  }
]

2. 内容脚本监听SPA路由变化

修改script.js,监听浏览器前进后退事件,并拦截前端路由跳转方法,检测到目标URL时执行重定向:

// 监听浏览器前进/后退触发的路由变化
window.addEventListener('popstate', checkAndRedirect);

// 重写pushState,监听主动发起的前端路由跳转
const originalPushState = history.pushState;
history.pushState = function(...args) {
  originalPushState.apply(this, args);
  checkAndRedirect();
};

// 重写replaceState,覆盖路由替换场景
const originalReplaceState = history.replaceState;
history.replaceState = function(...args) {
  originalReplaceState.apply(this, args);
  checkAndRedirect();
};

// 核心检查与重定向逻辑
function checkAndRedirect() {
  const currentUrl = window.location.href;
  if (currentUrl.startsWith('https://www.instagram.com/reels') && currentUrl !== 'https://www.instagram.com') {
    window.location.href = 'https://www.instagram.com';
  }
}

// 页面加载完成后先执行一次检查
document.addEventListener('DOMContentLoaded', checkAndRedirect);

3. 更新manifest.json的内容脚本匹配规则

确保内容脚本能覆盖Instagram的所有子路径,修改content_scripts的matches字段:

"content_scripts": [
  {
    "matches": [
      "https://www.instagram.com/*",
      "https://www.youtube.com/*"
    ],
    "js": ["script.js"]
  }
]

验证场景

  • 直接访问https://www.instagram.com/reels或https://www.instagram.com/reels/xxx,确认触发重定向;
  • 在Instagram首页点击reels按钮,观察URL变化后是否自动跳转首页;
  • 使用浏览器前进/后退到reels路径,确认重定向生效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 16:12:53