开源地址
安装
npm i electron-tabs
调整
修改main.js
1 2 3 4 5
| const mainWindow = new electron.BrowserWindow({ webPreferences: { webviewTag: true } });
|
修改html
1 2 3
| <tab-group></tab-group>
<script src="node_modules/electron-tabs/dist/electron-tabs.js"></script>
|
应用
封装部分方法 TabHelper.ts,更多内容根据官方文档方法结合实际情况调整
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
| import { TabGroup, TabOptions } from "electron-tabs"; const { ipcRenderer } = require("electron"); class TabHelper { tabGroup: TabGroup; constructor() { const tryTabGroup: TabGroup | null = document.querySelector("tab-group"); if (!tryTabGroup) { throw new Error("no tabgroup"); } this.tabGroup = tryTabGroup; } getCurrentTab() { return this.tabGroup.getActiveTab(); } getCurrentWebView() { return this.currentTab().webview as WebView; } getActiveUrl() { const url = this.currentWebView().src; const result = url.split("?")[0]; return result; } getTitle() { return this.currentTab().title; } getSiteTitle() { const title = this.currentWebView().getTitle(); const t = title.split("-")[0]; return t; } add(title: string, src: string, ...args: TabOptions[]) { const obj = { title, src, webviewAttributes: { allowpopups: true, }, active: true, ...args[0], }; const tab = this.tabGroup.addTab(obj); tab.once("webview-ready", () => { ipcRenderer.send("new-tab", id); }); } close() { this.currentTab().close(false); } } export const tab = new TabHelper();
|
main.js 里设置接受创建标签页的消息,这里用到了electron的进程通信,更多请看官方文档
1 2 3 4 5 6 7 8 9 10 11 12
| const { webContents } = require("electron");
ipcMain.on("new-tab", (event, webContentsId) => { const tabWebContents = webContents.fromId(webContentsId); tabWebContents.setWindowOpenHandler(({ url }) => { if (url.indexOf("about:blank") < 0) { tabWebContents.loadURL(url); }
return { action: "deny" }; }); });
|