如何在 Electron 应用程序中添加自定义标题栏?

3
我想创建一个定制的标题栏/控件,用于在 Electron 应用中加载的远程 URL 上方显示。
例如,假设我有一个名为 title.html 的文件:
<div>
    <button onclick="window.history.forward()">Go Forward</button>
    <button onclick="window.history.back()">Go Back</button>
</div>

假设我在我的 Electron 应用程序中加载 YouTube URL:

const createWindow = () => {
    const window = new BrowserWindow({
        width: 800,
        height: 600,
        titleBarStyle: 'hiddenInset',
    })

    window.loadURL('https://youtube.com')
}

如何使我的title.html始终显示在YouTube上方,以便我可以添加返回和前进按钮以及其他内容?

1个回答

2
我认为这里的策略是将你的 title.html 加载到 BrowserWindow 中,然后创建一个适当位置的承载 YouTube 的 BrowserView。 (在我的应用程序中,我使用 frame: false 而不是 hiddenInset,但希望类似的想法也可以适用于这里)
import * as path from "path";
import { BrowserWindow, BrowserView } from "electron";

const TITLEBAR_HEIGHT = 50; // px

const createWindow = () => {
    const window = new BrowserWindow({ width: 800, height: 600, titleBarStyle: 'hiddenInset' })
    const browserView = new BrowserView({ webPreferences: { sandbox: true, contextIsolation: true });
    window.setBrowserView(browserView);
    
    // load your titlebar page
    await window.loadFile(path.join(__dirname, "./index.html"))

    // position the titlebar
    const contentBounds = window.getContentBounds();
    browserView.setBounds({ x: 0, y: 0, width: contentBounds.width, height: contentBounds.height - TITLEBAR_HEIGHT });
    browserView.setAutoResize({ width: true, height: true });

    browserView.loadURL('https://youtube.com');    
}

您可以在样式表中设置标题栏的高度:

<div id="titlebar>
    ...
</div>

#titlebar {
    height: 50px;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接