electron中加载html,electron页面加载函数loadFile

在electron迎来3.0之际,一些备受诟病的函数和特性,也获得了改善和提升。其中,最显著的莫过于每个electron的一个入口函数了,那就是loadUrl()函数。目前最新的electron3.x系列,支持一个新的函数叫做loadFile(),简直是比原来的loadUrl()加载本地页面不知道要好用多少倍。

8b45a0725e34eb9012f9cb9ae48630bb.png

低版本electron不支持loadFile

在1.x和2.x的electron中,如果要使用loadFile函数,就会报错unknown function。

5a07b568d2aa430b145fd7b755acaa2f.png

Uncaught Exception:

TypeError: mainWindow.loadFile is not a function

at App.createWindow (/Users/sunan/Downloads/electron-quick-start-master/main.js:13:14)

at emitTwo (events.js:130:20)

at App.emit (events.js:213:7)

loadFile 对比 loadUrl

main.js:

mainWindow =

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Electron 项目,如果使用 Vue.js 作为前端框架,在启动应用程序时可能会遇到加载白屏的问题。这通常是由于 Vue.js 构建后的代码需要在本地运行,而 Electron 默认情况下不会加载本地文件。 解决这个问题的方法是在主进程Electron 添加一个本地文件访问协议(file://),并将访问限制设置为允许所有来源。可以在主进程添加以下代码: ```javascript const {app, BrowserWindow} = require('electron') const path = require('path') app.commandLine.appendSwitch('disable-site-isolation-trials'); app.commandLine.appendSwitch('disable-features', 'OutOfBlinkCors'); function createWindow () { const win = new BrowserWindow({ width: 800, height: 600, webPreferences: { webSecurity: false // 允许加载本地文件 } }) // 加载 Vue.js 打包后的 HTML 文件 win.loadFile(path.join(__dirname, 'dist', 'index.html')) // 打开开发者工具 win.webContents.openDevTools() } app.whenReady().then(() => { createWindow() app.on('activate', () => { if (BrowserWindow.getAllWindows().length === 0) { createWindow() } }) }) app.on('window-all-closed', () => { if (process.platform !== 'darwin') { app.quit() } }) ``` 在这个例子,我们为 `BrowserWindow` 的 `webPreferences` 添加了 `webSecurity: false`,这样就允许加载本地文件了。同时,在 `createWindow` 函数,我们使用 `loadFile` 方法加载 Vue.js 打包后的 HTML 文件,该文件位于 `dist/index.html`。最后,我们打开开发者工具(`win.webContents.openDevTools()`)以方便调试。 需要注意的是,在生产环境,应该将 `webSecurity` 设置为 `true`,以避免安全问题。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值