监听并拦截所有webview的打开窗口请求,然后在新的webview打开它。

This commit is contained in:
Allen 2025-05-12 01:41:53 +08:00
parent f99c1bb88e
commit cfb0f05ff1
4 changed files with 32 additions and 1 deletions

View File

@ -1,3 +1,4 @@
import { WebviewTag } from 'electron';
import { TabGroup, Tab } from 'electron-tabs';
// 菜单项
@ -225,3 +226,21 @@ async function initialize() {
// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', initialize);
window.electronAPI.onOpenTab((webContentId: number, url: string) => {
addTab(tabGroup, {
Url: url,
ShowName: '新标签页',
IconConfig: { _1x: { Default: '', Selected: '' }, _2x: { Default: '', Selected: '' } },
Children: null
}).then(tab => {
// 在加载完成后,获取标题
tab.once('webview-dom-ready', (detail: string) => {
console.log('webview-dom-ready detail:', detail);
const webview = tab.webview as WebviewTag;
const title = webview.getTitle();
tab.setTitle(title);
console.log('webview-dom-ready title:', title);
});
});
});

View File

@ -135,6 +135,14 @@ const createWindow = () => {
// });
// });
win.webContents.on('did-attach-webview', (event, webContents) => {
webContents.setWindowOpenHandler((details) => {
console.log('webview-new-window', webContents, details);
win.webContents.send('webview-new-window', webContents.id, details.url);
return { action: 'deny' };
});
});
// Set session
win.webContents.session.setPermissionRequestHandler((webContents, permission, callback) => {
callback(true);

View File

@ -4,6 +4,9 @@
import { contextBridge, ipcRenderer } from 'electron';
contextBridge.exposeInMainWorld('electronAPI', {
onOpenTab: (callback: (webContentId: number, url: string) => void) => {
ipcRenderer.on('webview-new-window', (_event, webContentId, url) => callback(webContentId, url));
},
// 检查URL是否可用
checkUrlAvailable: (url: string) => ipcRenderer.invoke('check-url-available', url),
@ -29,4 +32,4 @@ contextBridge.exposeInMainWorld('electronAPI', {
clearSessionStorage: () => {
window.sessionStorage.clear();
}
});
});

View File

@ -1,4 +1,5 @@
export interface ElectronAPI {
onOpenTab: (callback: (webContentId: number, url: string) => void) => void;
checkUrlAvailable: (url: string) => Promise<{ ok: boolean; status: number; error?: string }>;
setWebviewCookie: (url: string, cookie: string) => Promise<boolean>;
setSessionStorage: (key: string, value: string) => void;