Electron 不允许 windowswebSecurity: true
加载本地文件。
糟糕的解决方案
消除错误的一种方法是将其简单地设置为false
。但这会使您的应用程序使用起来不太安全:
new BrowserWindow({
...
webPreferences: {
webSecurity: false
}
})
好的解决方案
相反,您需要做的是创建一个自定义协议,然后使用它来加载文件。
第 1 步:创建自定义协议
主要流程:
import { protocol } from 'electron'
...
app.on('ready', async () => {
// Name the protocol whatever you want.
const protocolName = 'your-app-name'
protocol.registerFileProtocol(protocolName, (request, callback) => {
const url = request.url.replace(`${protocolName}://`, '')
try {
return callback(decodeURIComponent(url))
}
catch (error) {
// Handle the error as needed
console.error(error)
}
})
...
Note:我不确定协议名称是否必须是唯一的,我从未测试过。如果您只是将协议命名为safe-protocol
并且您的应用程序的用户有另一个已注册的应用程序 Xsafe-protocol
,您的应用程序要么在打开时抛出错误,要么会注册这两个应用程序,但当用户尝试从 URL 打开其应用程序时,使用app.setAsDefaultProtocolClient
功能,这两个应用程序都会打开。不确定在这种情况下会发生什么。
第二步:使用协议加载文件
方法一:从主进程获取路径:
主要流程:
ipcMain.on('open-file-dialog', function (event) {
const window = BrowserWindow.getFocusedWindow();
dialog.showOpenDialog(window, { properties: ['openFile'] })
.then(result => {
// Send the path back to the renderer
event.sender.send('open-file-dialog-reply', { path: result.filePaths[0] })
})
.catch(error => {
console.log('Could not get file path')
})
})
渲染器进程:
<img id="image-1">
ipcRenderer.on('open-file-dialog-reply', (event, data) => {
const path = data.path
loadImage(path)
}
function loadImage (path) {
const image1 = document.getElementById('image-1')
image1.src = `safe-file-protocol://${path}`
}
方法2:直接在渲染器中加载路径:
渲染器进程:
<img id="image-1" data-path="C:/test.jpg">
function loadImage () {
const image1 = document.getElementById('image-1')
const path = image1.dataset.path
image1.src = `safe-file-protocol://${path}`
}
loadImage()