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

