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

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

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 = new BrowserWindow({width: 800, height: 600})都是加载本地的index.html页面,loadFile 和 loadUrl对比如下:
electron3.x写法:
mainWindow.loadFile('index.html')传统2.x及1.x中的写法:
// and load the index.html of the app.const path = require('path')
const url = require('url')
mainWindow.loadURL(url.format({
pathname: path.join(__dirname, 'index.html'),
protocol: 'file:',
slashes: true
}))
特别提示
对于简写的loadFile('index.html'),因为是相对路径。所以,特殊情况下,会导致相对出别的首页的问题。所以,最好还是写绝对路径。苏南大叔个人建议,碰到显示默认首页,而不是你自己写的那个首页的时候,请想想苏南大叔的这段话。
const path = require('path')mainWindow.loadFile(path.join(__dirname, 'index.html'))
下面的这个截图,其实是个错误的loadfile,并没有load到苏南大叔自己写的那个页面。就是因为没有写绝对地址,而是写的相对地址的缘故。这个截图来自:使用vscode调试主进程的时候。

loadURL的另外两个例子
加载远程URL:
win.loadURL('https://github.com')加载本地HTML文件:
win.loadURL(`file://${__dirname}/app/index.html`)总结
经过对比,苏南大叔表示:这个新的loadFile函数,真心是好用到爆了。
以上是 electron页面加载函数loadFile 的全部内容, 来源链接: utcz.com/a/119143.html

