-
通過菜單切換
main.js
const { app, BrowserWindow, Menu, MenuItem, shell } = require('electron')
const path = require('path')
// 保持一個對於 window 對象的全局引用,不然,當 JavaScript 被 GC,
// window 會被自動地關閉
var mainWindow = null;
// 當所有窗口被關閉了,退出。
app.on('window-all-closed', function() {
// 在 OS X 上,通常用戶在明確地按下 Cmd + Q 之前
// 應用會保持活動狀態
if (process.platform != 'darwin') {
app.quit();
}
});
// 當 Electron 完成了初始化並且准備創建瀏覽器窗口的時候
// 這個方法就被調用
app.on('ready', function() {
// 創建瀏覽器窗口。
mainWindow = new BrowserWindow({
width: 800,
height: 800,
// frame: false, // windows下隱藏導航欄
// titleBarStyle: 'hidden', // mac下隱藏導航欄
webPreferences: {
nodeIntegration: true, // 是否啟用Node integration. 5.0以后默認值為 false.
contextIsolation: false, // 設置為false后,才能在渲染進程使用Electron API
preload: path.join(__dirname, 'preload.js')
}
});
});
// 設置系統菜單
// 切換頁面的函數
const sendMenuEvent = (url) => {
mainWindow.webContents.send('change-view', url);
}
const menuTemplate = [
{
label: '首頁',
click: async () => {
//在electron窗口內打開首頁
mainWindow.loadURL(path.join(__dirname, 'index.html'));
}
},
{
label: '父級',
submenu: [
{
label: 'electron窗口內打開百度',
click: async () => {
//在electron窗口內打開百度
sendMenuEvent('http://www.baidu.com');
},
},
{
label: '默認瀏覽器打開百度',
click: async () => {
//在默認瀏覽器打開新的窗口
await shell.openExternal('http://www.baidu.com');
},
}
]
}
]
const list = Menu.buildFromTemplate(menuTemplate)
Menu.setApplicationMenu(list);
preload.js
const { ipcRenderer } = require('electron')
// 在electron窗口內切換頁面
if(window && window.process && window.process.type === 'renderer') {
ipcRenderer.on('change-view', (event, url) => {
window.location.href = url;
});
}
以上是用electron打開新窗口
下面用js打開新窗口:
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- 安全設置 --> <meta http-equiv="Content-Security-Policy" content="default-src 'self' 'unsafe-inline';"> <title>Document</title> </head> <body> <script> // js切換窗口 baidu.addEventListener('click', () => { window.open('http://www.baidu.com', '_self') }) // 在新窗口打開頁面 baidu2.addEventListener('click', () => { window.open('http://www.baidu.com', '_blank') }) </script> </body> </html>
效果:


-
