WebView2打开新窗口的问题tab禁止弹窗

本文介绍了一个简单的C#应用程序,该程序使用Microsoft WebView2组件加载并显示来自优快云的一个特定博客页面。通过实例展示了如何初始化WebView2控件、加载网页以及处理新窗口请求。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.Web.WebView2.Core;
using Microsoft.Web.WebView2.WinForms;
namespace chome
{
    public partial class FMTEST : Form
    {
        public FMTEST()
        {
            InitializeComponent();
        }
        
        private async void FMTEST_LoadAsync(object sender, EventArgs e)
        {
            webView21.Source = new Uri("https://blog.youkuaiyun.com/ccagy");
            await webView21.EnsureCoreWebView2Async();
            webView21.CoreWebView2.NewWindowRequested += CoreWebView2_NewWindowRequested;
        }
        private void CoreWebView2_NewWindowRequested(object sender,CoreWebView2NewWindowRequestedEventArgs e)
        {
            //e.NewWindow = webView22.CoreWebView2;
            //在第二个webview2上面打开这个新窗口
            webView22.Source = new Uri(e.Uri.ToString());
            e.Handled = true;//禁止弹窗

        }
    }
}

const { app, BrowserWindow, ipcMain, session, shell,protocol } = require('electron') const createWindow = () => { const win = new BrowserWindow({ width: 1200, height: 800, frame: false, webPreferences: { nodeIntegration: true, contextIsolation: false, webviewTag: true, partition: String(+new Date()), } }) win.loadFile('index.html') // 拦截新开窗口的请求 win.webContents.setWindowOpenHandler(({ url }) => { console.log('拦截到新窗口请求:', url); win.webContents.send('new-tab', url); return { action: 'deny' }; }); // 监听 webview新窗口请求 win.webContents.on('did-attach-webview', (event, webContents) => { console.log('webview attached'); webContents.setWindowOpenHandler(({ url }) => { console.log('webview 拦截到新窗口请求:', url); win.webContents.send('new-tab', url); return { action: 'deny' }; }); }); return win; } app.whenReady().then(() => { const win = createWindow() app.on('activate', () => { if (BrowserWindow.getAllWindows().length === 0) { createWindow() } }) // 窗口控制逻辑 ipcMain.on('control-window', (event, command) => { const window = BrowserWindow.getFocusedWindow() if (!window) return switch (command) { case 'minimize': window.minimize() break case 'maximize': window.isMaximized() ? window.restore() : window.maximize() break case 'close': // window.close() app.quit(); break } }) // 设置代理 ipcMain.on('set-proxy', async (event, config) => { console.log('设置代理:', config); try { const ses = session.fromPartition('persist:agent'); // 设置代理规则 await ses.setProxy({ proxyRules: `http://${config.host}:${config.port}`, proxyBypassRules: 'localhost,127.0.0.1' }); console.log('代理设置成功'); event.reply('proxy-set-success', config); } catch (error) { console.error('代理设置失败:', error); event.reply('proxy-set-error', error.message); } }); // 清除代理 ipcMain.on('clear-proxy', (event) => { console.log('清除代理,使用本地网络'); // 必须使用与设置代理相同的分区会话 const ses = session.fromPartition('persist:agent'); // 仅需设置 mode: 'direct' 即可清除所有代理 ses.setProxy({ mode: 'direct' }) .then(() => { console.log('代理已清除'); // 通知渲染进程清除成功 event.reply('proxy-cleared'); }) .catch(err => { console.error('清除代理失败:', err); // 通知渲染进程错误信息 event.reply('proxy-clear-error', err.message); }); }); }) app.on('window-all-closed', () => { if (process.platform !== 'darwin') { app.quit() } }) 请在代码中
最新发布
10-25
### 如何在 WebView2 中配置和管理新窗口打开方式 #### 使用 `CoreWebView2.NewWindowRequested` 事件处理新窗口请求 为了控制 WebView2 控件中新窗口的创建行为,可以利用 `NewWindowRequested` 事件。当网页尝试通过 JavaScript 的 `window.open()` 或者目标属性为 `_blank` 的链接来打开新的浏览器实例时会触发此事件[^3]。 ```csharp webView.CoreWebView2.NewWindowRequested += (sender, args) => { // 阻止默认的新窗口操作 args.Handled = true; // 创建一个新的 WebView2 实例用于展示新页面 var newWebView = new Microsoft.Web.WebView2.WinForms.WebView2(); // 初始化并导航到指定 URL await InitializeAsync(newWebView); newWebView.Source = args.Uri; }; ``` #### 动态调整现有 WebView 显示内容而不开启新窗口 如果希望在同一 WebView 上加载原本应该在一个全新窗口中显示的内容,则可以在上述事件处理器内改变当前 WebView 的源地址: ```csharp webView.CoreWebView2.NewWindowRequested += (sender, args) => { args.Handled = true; // 停止默认动作 webView.Source = args.Uri; // 更新当前 WebView 的 URL }; ``` 这种方法适用于那些不需要多个独立浏览上下文的应用场景,在单个视图里顺序切换不同页面即可满足需求的情况。 #### 利用路由机制管理多 WebView 应用布局 对于更复杂的应用结构设计,比如模仿传统桌面应用中的选项卡功能或是构建一个多面板式的用户界面来说,可能还需要引入额外的逻辑层来进行各个 WebView 组件之间的协调工作。这通常涉及到定义一套内部路由规则以及相应的控制器类负责响应来自前端的不同类型的跳转指令,并据此动态增删对应的可视化组件[^4]。
评论 2
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

xcagy

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值