Custom procotol in Electron to replace file protocol for Angular app in production

Discussão em 'Angular' iniciado por JulieMarie, Fevereiro 12, 2025.

  1. JulieMarie

    JulieMarie Guest

    I've created an Angular app in Electron and everything has been working great until now. For security reasons, I've disabled the Electron fuse grantFileProtocolExtraPrivileges which means I can no longer do this to serve the app in production:

    // load the index.html of the app.
    if (!App.application.isPackaged) {
    App.mainWindow.loadURL(`http://localhost:${rendererAppPort}`);
    } else {
    App.mainWindow.loadURL(
    format({
    pathname: join(__dirname, '..', rendererAppName, 'index.html'),
    protocol: 'file:',
    slashes: true,
    })
    );
    }


    I thought the solution was to replace this with a custom protocol, but I can't figure out how to do that correctly. Here protocol|Electron, it gives this as an example for implementing a protocol that has the same effect as the file:// protocol:

    const { app, protocol, net } = require('electron')
    const path = require('node:path')
    const url = require('node:url')

    app.whenReady().then(() => {
    protocol.handle('foo', (request) => {
    const filePath = request.url.slice('foo://'.length)
    return net.fetch(url.pathToFileURL(path.join(__dirname, filePath)).toString())
    })
    })


    and I tried doing something like this:

    protocol.handle('foo', (request) => {
    const filePath = request.url.slice('foo://'.length);
    return net.fetch(url.pathToFileURL(path.join(__dirname, '..', rendererAppName, filePath)).toString());
    })


    and then:

    App.mainWindow.loadURL(`foo://index.html`);


    But it's just not working. It packages up the app and when I run it, it's just a blank white window. My logs don't show any errors. I've searched the internet, but I can't figure out where the problem is.

    Any ideas? I feel as though it's something super simple at this point. :-/

    Continue reading...

Compartilhe esta Página