前言:
請確保已搭建好vue+electron的一個項目,詳情參考:用vue-cli+Electron開發桌面應用(搭建vue項目、安裝electron),更多相關信息,參考作者往期博客
具體描述
- 將
loadpage.html
作爲加載頁面,該頁面主要是無邊窗口loading
的頁面佈局和樣式,存在項目的public文件夾下 webContents.loadURL(url[, options]),在窗口中加載url, url必須包含協議前綴,比如http://或file://.如果加載想要忽略http緩存,可以使用pragma頭來達到目的.
background.js設置如下:
import { app, protocol, BrowserWindow, ipcMain, Menu} from 'electron'
import {
createProtocol
} from 'vue-cli-plugin-electron-builder/lib'
const isDevelopment = process.env.NODE_ENV !== 'production'
let win
let loading
protocol.registerSchemesAsPrivileged([{ scheme: 'app', privileges: { secure: true, standard: true }}])
function createWindow() {
win = new BrowserWindow({
width: 1122,
height: 670,
show: false, // 一開始是false,loadpage加載完畢的時候爲true
webPreferences: {
nodeIntegration: true,
webSecurity: false // 允許跨域
}
})
if (process.env.WEBPACK_DEV_SERVER_URL) {
setTimeout(() => { // 關閉loadpage的時候,將win, show true
loading.hide()
loading.close()
win.show()
win.loadURL(process.env.WEBPACK_DEV_SERVER_URL)
}, 5000)
win.webContents.closeDevTools()
} else {
setTimeout(() => {
loading.hide()
loading.close()
win.show()
createProtocol('app')
win.loadURL('app://./index.html')
}, 5000)
win.webContents.closeDevTools() // 關閉調試模式
}
win.on('closed', () => {
win = null
app.quit();
})
win.on('close', function(_event) {
app.quit();
})
}
function showLoading(callback) {
loading = new BrowserWindow({
show: false,
frame: false,
width: 360,
height: 360,
resizable: false
})
loading.once('show', callback)
loading.loadURL(`file://${__static}/loadpage.html`) // 將loadpage作爲加載頁面,該頁面存在項目的public文件夾下
loading.show()
}
function initApp() {
showLoading(createWindow)
}
app.on('activate', () => {
if (win === null) {
initApp()
}
})
app.on('ready', async() => {
initApp()
})
更多信息參考:項目中的background.js文件。