首页 > 解决方案 > Electron - 使用 showOpenDialog 时抛出不允许加载本地资源

问题描述

我只是想使用showOpenDialog和加载图像。但是当我选择一个图像应用程序会崩溃。

主.js:

...
  ipcMain.on('open-file-dialog', function (event) {
    const window = BrowserWindow.getFocusedWindow();

    dialog.showOpenDialog(window, {
      properties: ['openFile']
    }, p => {
      console.log(p)
    });
  })

渲染器.js:

document.querySelector('#select-image').addEventListener('click', function (event) {
    ipcRenderer.send('open-file-dialog')
});

当我选择任何此错误显示在控制台中时: Not allowed to load local resource: file:///start 并且电子版本是8.2.5

编辑1:

此警告(或可能是错误)显示在终端中objc[50899]: Class FIFinderSyncExtensionHost is implemented in both /System/Library/PrivateFrameworks/FinderKit.framework/Versions/A/FinderKit (0x7fff951e61d0) and /System/Library/PrivateFrameworks/FileProvider.framework/OverrideBundles/FinderSyncCollaborationFileProviderOverride.bundle/Contents/MacOS/FinderSyncCollaborationFileProviderOverride (0x11298bdc8). One of the two will be used. Which one is undefined.

编辑 2:我使用 Electron Fiddle 将示例 Gist 放在一起:这里

标签: electron

解决方案


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)
    }
  })
  ...

注意:我不确定协议名称是否必须是唯一的,我从未测试过它。如果您只是将协议命名为safe-protocol并且您的应用程序的用户有另一个应用程序 X 已注册safe-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}`
}

方法二:直接在渲染器中加载路径:

渲染器过程:

<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()

推荐阅读