Skip to content

Not allowed to load local resource: file://index.html/ after webpacking main.js #5107

Closed
@MihaiValentin

Description

@MihaiValentin

I am trying to webpack all the main.js script & its dependencies in a single file (I want to have one file for the UI app, and one file for the server app).

If I use the normal source, index.html loads just fine. However, when webpacking, I get the error mentioned in the title.

Here's the webpack config I used:

webpack({
    entry: [
        './main'
    ],
    output: {
        path: path.join(__dirname, 'asar'),
        filename: 'main.js',
        libraryTarget: 'commonjs2'
    },
    externals: ['electron'],
    target: 'node'
});

I load the file like this:
mainWindow.loadURL('file://' + __dirname + '/index.html');

I think that its perhaps due to webpack calling/evaling stuff outside of the electron context that allows serving local files.

Any ideas/suggestions? Thanks!

  • Electron version: 0.37.2
  • Operating system: Windows 10 Home

Activity

zcbenz

zcbenz commented on Apr 11, 2016

@zcbenz
Contributor

You can probably try turning off webSecurity in webPreferences of BrowserWindow. For more questions I suggest seeking help from the community.

singhshashi

singhshashi commented on Jun 25, 2016

@singhshashi

@MihaiValentin Hey, did you find a solution for this?

eiriarte

eiriarte commented on Jun 29, 2016

@eiriarte

@MihaiValentin @singhshashi I had the same problem. It seems webpack, by default, tries to "mock" Node globals like __dirname. I disabled this behavior with the node.__dirname option and… it worked!

Just in case, I'm also using webpack-target-electron-renderer for the target option.

This is my config so far. I hope it helps:

var webpack = require('webpack');
var path = require('path');
var webpackTargetElectronRenderer = require('webpack-target-electron-renderer');

var BUILD_DIR = path.resolve(__dirname, 'build');
var APP_DIR = path.resolve(__dirname, 'src');

var config = {
  entry: APP_DIR + '/index.js',
  output: {
    path: BUILD_DIR,
    filename: 'index.js'
  },
  node: {
    __dirname: false,
    __filename: false
  },
  module : {
    loaders : [
      {
        test : /\.jsx?/,
        include : APP_DIR,
        exclude: /node_modules/,
        loader : 'babel'
      }
    ]
  }
};

config.target = webpackTargetElectronRenderer(config);

module.exports = config;
singhshashi

singhshashi commented on Jun 30, 2016

@singhshashi

@eiriarte Thanks for sharing that, however that did not work. If I pack the files for the main process using webpack, even with the node configuration that you have said, I still get the same error.

I am sharing a workaround that I am using to get around the issue for others who land on this thread.

Instead of using es features which require babel to transpile them to work correctly in the main. js file, I separated these out into different files. In my main.js I do not use any features which require babel transpilation. So instead of import I use require. For code which was using es7 proposal features such as async, I moved that code to different files, within a folder called desktopServices (you could come up with a better name). I now run webpack to create a bundle for desktopServices and I reference this bundle in main.js.

const myshell = require('./dist/desktopServices').myShell;

My webpack.config.main.js file contains the following config.


let config = {
  target:'electron',
  entry:'./desktopServices/desktopServices.js',
  output:{
    path:path.resolve(__dirname, 'dist'),
    filename: 'desktopServices.js',
    publicPath:'/dist/',
    libraryTarget:'commonjs2'
  },
  resolve: {
    extensions:["",".js",".json"]
  },
  module: {
    noParse: /node_modules\/json-schema\/lib\/validate\.js/,
    loaders:[{
      test: /\.js?$/,
      exclude: /node_modules/,
      loader: 'babel-loader'
    },
      {
        test: /\.json/,
        loader: 'json-loader',
      },
    ],
  },
}

module.exports = config;

Not the cleanest way, but I guess this is the route I am taking for the time being till some of the es features I want to use get incorporated into node and don't require babel transpilation.

rob3c

rob3c commented on Dec 13, 2016

@rob3c

For me, it turned out to be a misleading error. I was getting the not allowed to load local resource error because webpack hadn't finished writing the file before I was trying to load it, not because it was there with the wrong permissions.

I fixedwrapped it with setTimeout (the duct tape of javascript) so I could get on with life:

setTimeout(() => {
  win.loadURL(`file:///${__dirname}/index.html`);
}, 2000); // 1 second wasn't enough lol
milewski

milewski commented on Dec 13, 2016

@milewski

for me.. the reason was because the path the webpack was outputting the bundle.. was out of reach... i solved it by coming back a few directories and applying the node config as suggested above.. works perfectly :D

pathname: path.join(__dirname, '../../source/resources/views', 'index.html');

node: {
    __dirname: false,
    __filename: false
  },
j-peterson

j-peterson commented on Feb 20, 2017

@j-peterson

FYI to those here via google: you get the same error if the file doesn't exist. I forgot to tell electron-packager to copy the target file into the app. Learn from my stupid mistakes :)

popey456963

popey456963 commented on May 8, 2017

@popey456963

For future reference (as I've searched through this page too many times), here are the current possible problems:

  1. The file doesn't exist, or your Node application can't reach it. Make sure electron-packager is copying the target file into the app!

  2. You might need to disable webSecurity within webPreferences when you create your BrowserWindow():

{
  webPreferences: {
    webSecurity: false
  }
}
  1. Webpack, by default, seems to try to "mock" node globals like node.__dirname, you can disable this by adding the following to your config:
  node: {
    __dirname: false
  }
  1. You can delay execution of loading the URL using setTimeout() (not recommended) or waiting for the ready event being sent from the app (better).
setTimeout(() => {
  win.loadURL(`file:///${__dirname}/index.html`);
}, 2000); // 1 second wasn't enough lol
app.on('ready', () => {
  win.loadURL(`file:///${__dirname}/index.html`);
})
ishwarrimal

ishwarrimal commented on May 24, 2017

@ishwarrimal

For me the solution was

  1. disable web security.
  2. when trying to concatenate file, i was doing __dirname+"./FileName". So it was creating 'C:/Folder./FileName'. So there should be no "./" instead just "/". This was not an issue in development and not until i added ASAR.
  3. It follows strict casing of file names. This issue i encountered after adding asar, till then it was working perfect in development as well as production.

Hope this helps someone nube like me.

17 remaining items

fatalmuffin

fatalmuffin commented on Jun 14, 2018

@fatalmuffin

Just thought I'd add, I also got this error due to my own blunder (cap sensitivity)
I was calling pathname: path.join(__dirname, 'Views/settingsWindow.html') when the file name was all lower case.

This only casued an error once it was webpacked.

it-arjan

it-arjan commented on Jan 7, 2019

@it-arjan

I tried some of the solutions but couldn't get it to work (using angular@7.x with electron@3.0.7).
I found the best solution in a post with only 3 votes on SO: Turns out there is no need for this package!
https://stackoverflow.com/questions/45041364/angular-electron-webpack-live-reloading

Zero config-hassle solution:
-npm uninstall electron-reload
-Run ng serve in one terminal
-in main.js change win.loadURL(http://localhost:4200/index.html);
-then run npm run electron in another terminal

It just WORKS

tyrants666

tyrants666 commented on Apr 21, 2019

@tyrants666

I Tried to fix this my whole day & finally this guys solution worked do check
electron-userland/electron-builder#2955 (comment)

proton1k

proton1k commented on Jun 3, 2019

@proton1k

When you define the "build" attribute in the package.json, just add required files as following:

    "files": [
      "./build/**/*",
      "./index.html",
      "./src/*.js"
    ],

Then the electron-builder will pack it correctly.

TheDigiBusiness

TheDigiBusiness commented on Dec 4, 2019

@TheDigiBusiness

Turned out for that the 'file://' prefix was all i needed for the loadUrl method.
Had:
win.loadUrl(path.join(__dirname, "./index.html"))
Replaced with:
win.loadUrl(path.join("file://",__dirname, "./index.html"))

bonniss

bonniss commented on Jun 8, 2020

@bonniss

Webpack baffles me mixing both forward and backward slashes in the URL to the html entry, so I use node's url and path to make it work:

const winURL = process.env.NODE_ENV === 'development'
  ? 'http://localhost:9080'
  : url.format({
    protocol: 'file',
    pathname: path.join(__dirname, 'index.html'),
  });
cnscorpions

cnscorpions commented on Dec 8, 2020

@cnscorpions

it is a disaster, I am stuck in CRA + electron 😂, running in dev mode is okay, but packaged into windows exe does not work at all.

cnscorpions

cnscorpions commented on Dec 8, 2020

@cnscorpions

I got it. 🤣 If you use CRA with react-router, you should use HashRouter, not BrowerRouter. DONE!!! 😂 refer to electron-userland/electron-builder#2167

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @omenking@PierBover@singhshashi@zcbenz@rob3c

        Issue actions

          Not allowed to load local resource: file://index.html/ after webpacking main.js · Issue #5107 · electron/electron