读取本地图片
设置安全参数
- main
const { app, BrowserWindow } = require("electron");
const createWindow = () => {
const mainWindow = new BrowserWindow({
width: 1024,
height: 600,
webPreferences: {
// 设置安全参数
webSecurity: false, // false 之后就可以访问 本地资源文件了
},
});
mainWindow.loadURL("http://localhost:3000"); // 本地服务链接
mainWindow.webContents.openDevTools();
};
- renderer
<div>
<img src="D:/xxxx/xxx.png" />
访问本地图片地址
</div>
自定义协议
官方文档:https://www.electronjs.org/zh/docs/latest/api/protocol
- main
const { session, app, protocol } = require('electron')
const path = require('path')
app.whenReady().then(() => {
const partition = 'persist:example'
const ses = session.fromPartition(partition)
// 注册协议 aaaa 协议名字无所谓 自定义即可
ses.protocol.registerFileProtocol('自定义一个协议名', (request, callback) => {
const url = request.url.substr(7)
// 防止url 解析不正常 使用 decodeURI
callback({ path: path.normalize(`${__dirname}/${url}`) })
})
mainWindow = new BrowserWindow({ webPreferences: { partition } })
})
app.whenReady().then(() => {
// 注册协议 aaaa 协议名字无所谓 自定义即可
protocol.registerFileProtocol("aaaa", (request, callback) => {
const url = request.url.substr(7);
// 防止url 解析不正常 使用 decodeURI
callback(decodeURI(path.normalize(url)));
});
});
- renderer
<div>
<img src="D:/xxxx/xxx.png" />
访问本地图片地址
</div>
electron-forge
electron-forge是 electron 的脚手架,类似于,react 的create-react-app
或者 vue 的vue-cli
,所有配置文件都是已经配置好的,根据需求在往上添加就可以用了。如果加载本地磁盘资源用以上办法还是不太行的。需要再加上一个配置才行。
在forge.config.js
或者package.json
设置plugins
项,如下
{
"plugins": [
[
"@electron-forge/plugin-webpack",
{
"devContentSecurityPolicy": "`default-src 'self' 'unsafe-inline' data:;`", //设置 devContentSecurityPolicy 就可以访问本地资源了
"mainConfig": "./webpack.main.config.js",
"renderer": {
"config": "./webpack.renderer.config.js",
"entryPoints": [
{
"html": "./src/index.html",
"js": "./src/renderer.tsx",
"name": "main_window"
}
]
}
}
]
]
}