electron-vite-vue/packages/main/index.ts

71 lines
1.8 KiB
TypeScript
Raw Normal View History

import { app, BrowserWindow, shell } from 'electron'
import { release } from 'os'
import { join } from 'path'
2021-02-18 17:29:45 +08:00
// Disable GPU Acceleration for Windows 7
if (release().startsWith('6.1')) app.disableHardwareAcceleration()
// Set application name for Windows 10+ notifications
if (process.platform === 'win32') app.setAppUserModelId(app.getName())
2021-11-08 10:21:15 +08:00
if (!app.requestSingleInstanceLock()) {
app.quit()
process.exit(0)
}
2021-09-09 09:37:02 +08:00
let win: BrowserWindow | null = null
2020-08-16 20:42:52 +08:00
2021-12-30 10:30:50 +08:00
async function createWindow() {
2020-08-16 20:42:52 +08:00
win = new BrowserWindow({
title: 'Main window',
2020-08-31 09:50:57 +08:00
webPreferences: {
preload: join(__dirname, '../preload/index.cjs')
2020-08-31 09:50:57 +08:00
},
2020-08-16 20:42:52 +08:00
})
2021-09-09 09:37:02 +08:00
if (app.isPackaged) {
win.loadFile(join(__dirname, '../renderer/index.html'))
2021-09-09 09:37:02 +08:00
} else {
// 🚧 Use ['ENV_NAME'] avoid vite:define plugin
const url = `http://${process.env['VITE_DEV_SERVER_HOST']}:${process.env['VITE_DEV_SERVER_PORT']}`
2021-11-11 17:52:50 +08:00
win.loadURL(url)
2021-09-09 09:37:02 +08:00
win.webContents.openDevTools()
}
// Test active push message to Renderer-process
win.webContents.on('did-finish-load', () => {
win?.webContents.send('main-process-message', (new Date).toLocaleString())
})
// Make all links open with the browser, not with the application
win.webContents.setWindowOpenHandler(({ url }) => {
if (url.startsWith('https:')) shell.openExternal(url)
return { action: 'deny' }
})
2020-08-16 20:42:52 +08:00
}
2021-12-30 10:30:50 +08:00
app.whenReady().then(createWindow)
2021-09-09 09:37:02 +08:00
2021-09-09 09:50:18 +08:00
app.on('window-all-closed', () => {
win = null
if (process.platform !== 'darwin') app.quit()
2021-09-09 09:50:18 +08:00
})
2021-11-08 10:21:15 +08:00
app.on('second-instance', () => {
if (win) {
// Focus on the main window if the user tried to open another
2021-11-08 10:21:15 +08:00
if (win.isMinimized()) win.restore()
win.focus()
}
})
2021-12-30 10:30:50 +08:00
app.on('activate', () => {
const allWindows = BrowserWindow.getAllWindows()
if (allWindows.length) {
allWindows[0].focus()
} else {
createWindow()
}
})