如何解决Electron 中的多个窗口
我已经找了好几个小时了,但找不到一种方法来构建一个工作设置以在我的 Electron 应用程序中使用多个窗口。
我将 electron-forge
与普通的 JS 一起使用。没有反应或 vue。
我想要实现的是我可以使用函数从主应用程序仪表板内部触发的弹出窗口。
这是我对 HTML 的看法:
<i onclick="newBot()" class="fas fa-plus new-bot-button bar-icon"></i>
<i onclick="selectBot()" class="fas fa-Box-open select-bot-button bar-icon"></i>
<i onclick="startBot()" class="fas fa-play start-bot-button bar-icon"></i>
<i onclick="stopBot()" class="fas fa-stop stop-bot-button bar-icon"></i>
<i onclick="about()" class="fas fa-info about-button bar-icon"></i>
我对如何在 JavaScript 中实现这一点一无所知,因此不胜感激。
注意,我有一个预加载脚本 mainPreload.js
,主脚本是 main.js
。该窗口也是无框的,并且有一个我编码的自定义标题栏。它看起来像这样。上面引用的图标是最右边的一组。
这是我的main.js
:
const { ipcMain,app,browserWindow } = require('electron')
function createWindow () {
const win = new browserWindow({
width: 800,height: 600,resizable: false,webPreferences: {
preload: path.join(__dirname,'mainPreload.js'),nodeIntegration: true,contextIsolation: false
},frame: false,icon: './assets/toggle-01.png'
})
win.loadFile('index.html');
ipcMain.on('minimize',() => {
win.minimize()
});
}
app.whenReady().then(() => {
createWindow()
app.on('activate',() => {
if (browserWindow.getAllWindows().length === 0) {
createWindow()
}
})
})
app.on('window-all-closed',() => {
if (process.platform !== 'darwin') {
app.quit()
}
})
这是我的mainPreload.js
:
function scrollDown() {
document.getElementById('console-text').scrollTop = document.getElementById('console-text').scrollHeight
}
window.addEventListener('DOMContentLoaded',() => {
const container = document.getElementById('console-text');
console.log = function(message) {
const p = container.appendChild(document.createElement('p'));
p.textContent = message;
p.className = 'console-output';
scrollDown();
};
window.addEventListener('error',(error) => {
const p = container.appendChild(document.createElement('p'));
p.textContent = error.message;
p.className = 'console-output';
scrollDown();
});
console.log('Ready')
})
谢谢!
解决方法
要显示新窗口,您只需要创建新的 BrowserWindow 实例。你可以参考ElectronJS samples on GitHub
以下是基于创建窗口演示的代码。
为您的按钮添加一个 ID(顺便说一句,使用 <i>
标签不是最好的主意):
<i id="id-about" class="fas fa-info about-button bar-icon"></i>
然后创建一个点击事件处理程序。将此代码放入您的渲染器进程(在您的情况下是在您的 index.html
中运行的 JS)。
const {BrowserWindow} = require('electron').remote
const path = require('path')
const newWindowBtn = document.getElementById('id-about')
newWindowBtn.addEventListener('click',(event) => {
const modalPath = path.join('file://',__dirname,'../../sections/windows/about.html')
let win = new BrowserWindow({ width: 400,height: 320 })
win.on('close',() => { win = null })
win.loadURL(modalPath)
win.show()
})
希望这会有所帮助。您可以在ElectronJS Docs(特别是BrowserWindow)
中找到更多信息版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。