Electron-tabs标签页

发布时间:

更新时间:

开源地址

安装

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;
}
// 获取激活标签页里网页的title
getSiteTitle() {
const title = this.currentWebView().getTitle();
const t = title.split("-")[0];
return t;
}
// 创建一个标签页,标题和url
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" };
});
});
请吃小笼包
支付宝 | Alipay
微信 | Wechat