Electron - throws Not allowed to load local resource when using showOpenDialog

前端 未结 1 1906
-上瘾入骨i
-上瘾入骨i 2021-01-06 18:35

I just wanted to use showOpenDialog and load an image. But when I select an image app will crash.

main.js:



        
1条回答
  •  再見小時候
    2021-01-06 18:38

    Electron doesn't allow windows with webSecurity: true to load files. You could simply set it to false and get rid of the error but it would make your app unsafe to use.

    Instead, what you have to do is to create a custom protocol and then use that for loading files.

    Step 1: Create a custom protocol

    Main process:

    import { protocol } from 'electron'
    
    ...
    
    app.on('ready', async () => {
      // Name the protocol whatever you want
      const protocolName = 'safe-file-protocol'
    
      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)
        }
      })
      ...
    

    Step 2: use protocol to load files

    Method 1: get path from the main process:

    Main process:

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

    Renderer process:

    
    
    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}`
    }
    

    Method 2: load path directly in the renderer:

    Renderer process:

    
    
    function loadImage () {
      const image1 = document.getElementById('image-1')
      const path = image1.dataset.path
      image1.src = `safe-file-protocol://${path}`
    }
    
    loadImage()
    

    0 讨论(0)
提交回复
热议问题