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

如何开发Chrome扩展将JavaScript window.open的_blank等参数替换为_self

Chrome扩展实现方案

核心思路

直接hook页面原生的window.open方法,在方法调用时统一拦截替换目标参数,比逐个解析修改DOM中的链接代码覆盖更全面,实现更简单。

1. 编写扩展配置文件(manifest.json,V3版本)

{
  "manifest_version": 3,
  "name": "window.open目标替换工具",
  "version": "1.0",
  "description": "将window.open的_blank等新窗口目标参数替换为_self,强制在当前标签页打开",
  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["content.js"],
      "run_at": "document_start",
      "all_frames": true
    }
  ]
}

配置说明:run_at设为document_start保证在页面所有脚本执行前完成hook,all_frames设为true覆盖页面内iframe的调用场景。

2. 编写核心逻辑文件(content.js)

// 注入hook代码到页面上下文,保证能覆盖原生window.open
const injectScript = document.createElement('script');
injectScript.textContent = `
  // 保存原生window.open方法
  const originalWindowOpen = window.open;
  // 需要替换的目标参数列表,可按需扩展
  const replaceTargets = new Set(['_blank', '__blank', '_new', 'blank', 'new']);

  // 重写window.open方法
  window.open = function(url, target, features, ...rest) {
    // 匹配到需要替换的目标参数时统一改为_self
    if (target && replaceTargets.has(target.trim().toLowerCase())) {
      target = '_self';
    }
    // 调用原生方法执行后续逻辑
    return originalWindowOpen.call(this, url, target, features, ...rest);
  };
`;
// 立即注入到页面头部
document.documentElement.appendChild(injectScript);
injectScript.remove();

3. 扩展加载使用

  • 打开Chrome浏览器地址栏输入chrome://extensions/进入扩展管理页
  • 开启页面右上角「开发者模式」开关
  • 点击左上角「加载已解压的扩展程序」,选择存放上述两个文件的文件夹即可生效

本方案可以覆盖所有window.open调用场景,包括写在a标签href属性中的JavaScript调用、页面脚本主动调用、iframe内调用等情况。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 10:27:02