Dmitry
Dmitry

Reputation: 581

Electron + Angular = no local files?

My issue is hard to explain, but I'll try - I've got electron error Not allowed to load local resource when trying to playback mp3 file from the directory of application.

That happens because I'm using Webpack for development and Express server for production to run my apps (Express is used due to some Angular routing features).

This is part of my electron-main.js -

function createWindow() {
    win = new BrowserWindow({
    width: 1500,
    height: 900,
    resizable: true,
    center: true,
    autoHideMenuBar: true,
    icon: path.join(__dirname, 'static', 'note.ico')
  });

   if (DEBUG) {
     // Loading from Webpack
     win.loadURL(`http://localhost:4200`);
     win.webContents.openDevTools();
   }
   else {
     // Loading from Express-server
     const server = require("../server");
     win.loadURL(`http://localhost:3333`);
   }

server.js

let path = require('path');
let express = require('express');
let app = express();

app.use(express.static(path.join(__dirname, 'dist')));

app.get('/', function (req, res) {
  res.sendFile(path.join(__dirname, 'dist', 'index.html'));
});

app.listen(3333);

But when I tried to set

win.loadURL(url.format({
    pathname: path.join(__dirname, 'index.html'),
    protocol: 'file:',
    slashes: true
  }));

I've got my mp3 playback.

So I understand that local files can be accessed only when protocol: 'file:', not http: App structure should be similar -

(root folder)
--app.exe (whatever)
--mp3
  --1.mp3
  --2.mp3
  --3.mp3
  ...

Is there a workaround? Maybe I can use Express to get my files?

Upvotes: 0

Views: 782

Answers (1)

Dmitry
Dmitry

Reputation: 581

The only workaround I've found is to create additional hidden window using file: protocol like this

hiddenWindow = new BrowserWindow({
  show: false
});

hiddenWindow.loadURL(url.format({
  pathname: path.join(__dirname, 'hidden.html'),
  protocol: 'file:',
  slashes: true
}));

and init it's functions using ipcRenderer and ipcMain.

Upvotes: 1

Related Questions