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

Electron:webview中检测阻止新窗口打开并获URL(new-window事件无效)

在WebView的HTML/JS中拦截新标签页打开事件并获取目标URL

由于new-window是Electron中WebView组件在**宿主页面(主进程或渲染层宿主)**上监听的事件,无法在WebView加载的内容页面(你编写的HTML/JS代码)中直接使用。以下是两种在内容页面内实现拦截并获取目标URL的可行方案:

方案1:重写window.open方法

页面中通过脚本调用window.open()触发的新窗口打开请求,可以通过重写该方法直接拦截:

// 保存原始window.open方法
const originalWindowOpen = window.open;

// 重写方法实现拦截
window.open = function(targetUrl, target, features) {
  // 获取目标URL并处理
  console.log('拦截到window.open请求:', targetUrl);
  
  // 阻止默认新窗口创建
  return null;
};

方案2:拦截target="_blank"的链接点击

针对HTML中带有target="_blank"属性的链接,通过监听全局点击事件拦截:

document.addEventListener('click', (e) => {
  // 找到触发点击的<a>标签
  const linkElement = e.target.closest('a');
  
  if (linkElement && linkElement.target === '_blank') {
    // 阻止默认跳转行为
    e.preventDefault();
    
    // 获取目标URL
    const targetUrl = linkElement.href;
    console.log('拦截到新标签页链接:', targetUrl);
    
    // 可在此添加自定义逻辑,比如在当前页面打开、记录URL等
  }
});

补充:拦截表单提交到新窗口

如果存在通过target="_blank"提交的表单,也可以通过全局监听拦截:

document.addEventListener('submit', (e) => {
  const formElement = e.target;
  
  if (formElement.target === '_blank') {
    e.preventDefault();
    
    const targetUrl = formElement.action;
    console.log('拦截到表单提交的新窗口URL:', targetUrl);
    
    // 可自行处理表单数据和提交逻辑
  }
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 03:57:15