New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
MihaiValentin opened this Issue Apr 10, 2016 · 24 comments

Comments

Projects
None yet
@MihaiValentin

MihaiValentin commented Apr 10, 2016

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
@zcbenz

This comment has been minimized.

Contributor

zcbenz commented Apr 11, 2016

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

@zcbenz zcbenz closed this Apr 11, 2016

@singhshashi

This comment has been minimized.

singhshashi commented Jun 25, 2016

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

@eiriarte

This comment has been minimized.

eiriarte commented Jun 29, 2016

@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

This comment has been minimized.

singhshashi commented Jun 30, 2016

@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

This comment has been minimized.

rob3c commented Dec 13, 2016

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

This comment has been minimized.

milewski commented Dec 13, 2016

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

This comment has been minimized.

j-peterson commented Feb 20, 2017

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

This comment has been minimized.

popey456963 commented May 8, 2017

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

This comment has been minimized.

ishwarrimal commented May 24, 2017

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.

@PierBover

This comment has been minimized.

Contributor

PierBover commented Aug 10, 2017

I'm loading http://localhost:8080/ on my main browser window for the webpack dev server (so i can get hot module reloading). Problem was that when loading with the file:// protocol on an <iframe> it didn't work.

I simply disabled web security as pointed out by @popey456963 .

@omenking

This comment has been minimized.

omenking commented Nov 30, 2017

I have two configurations for webpack each for the electron-main and electron-renderer

const path = require('path');
const config_main = {
  target: 'electron-main',
  entry: path.resolve(__dirname, 'src/main/index.js'),
  output: {
    path    : path.resolve(__dirname, 'static'),
    filename: 'main.js'
  },
  externals: [{ 'electron-store': 'require("electron-store")' }],
  resolve: {
    alias: {
      main   : path.resolve(__dirname, 'src/main/'),
      common : path.resolve(__dirname, 'src/common/')
    }
  }
};

const config_renderer = {
  target: 'electron-renderer',
  entry: path.resolve(__dirname, 'src/renderer/index.js'),
  output: {
    path    : path.resolve(__dirname, 'static'),
    filename: 'renderer.js'
  },
  externals: [{ 'electron-store': 'require("electron-store")' }],
  resolve: {
    alias: {
      components : path.resolve(__dirname, 'src/renderer/components/'),
      core       : path.resolve(__dirname, 'src/renderer/core/'),
      states     : path.resolve(__dirname, 'src/renderer/states/'),
      ui         : path.resolve(__dirname, 'src/renderer/ui/'),
      common     : path.resolve(__dirname, 'src/common/'),
    }
  }
};

module.exports = [
  config_main,
  config_renderer
];

I have tried applying

  node: {
    __dirname: false
  },

I have console'd out in my renderer.js the __dirname and in both cases if I have __dirname set to false or true they both print out /

Of course if I manually put in the absolute url it works, though unsure why __dirname refuses to give the correct path.

Consideraetions

webpackTargetElectronRenderer is the same thing as target: electron-main

I believe at some point electron-main was rolled into webpack making webpackTargetElectronRenderer obsolute

Here you can see what electron-main does
https://github.com/webpack/webpack/blob/master/lib/WebpackOptionsApply.js#L70-L185

Here you can see exact same code.
https://github.com/chentsulin/webpack-target-electron-renderer/blob/master/index.js

@omenking

This comment has been minimized.

omenking commented Nov 30, 2017

Turns out I had

  node: {
    __dirname: false
  },

In my renderer config instead of my main config. I will keep my comment above in case anyone likes my config file.

@haykerman

This comment has been minimized.

haykerman commented Dec 19, 2017

What if I am not using webpack?

@popey456963

This comment has been minimized.

popey456963 commented Dec 20, 2017

@hbgdPro Try some of the options from #5107 (comment), 1, 2 and 4 all don't require webpack.

@haykerman

This comment has been minimized.

haykerman commented Dec 20, 2017

@popey456963 Thanks. I had already tried before I asked. My problem was actually I had to specify which folders I needed to include in build process. It has nothing to do with webpack.

@TheLarkInn

This comment has been minimized.

TheLarkInn commented Dec 22, 2017

I just came across this myself, (hi I'm from the webpack team). We have a electron-main target in webpack, and I did not know that the__dirname and __filename mocks break the default quick-start example.

Just to make sure, electron team. Would this be an official recommendation to have this disabled? If so I will go ahead and PR our defaults for the electron-main target that we have so that these builtins are not mocked.

Thanks!

@MarshallOfSound

This comment has been minimized.

Member

MarshallOfSound commented Dec 22, 2017

@TheLarkInn __dirname and __filename are super critical for most electron apps as they are used to find the path to the HTML file to show in the renderer process. Mocking them breaks things most/all the time. Not mocking them would fix many peoples problems 👍

@s-lawrence

This comment has been minimized.

s-lawrence commented Feb 3, 2018

For those not using Webpack i stumbled across a weird solution that i am hoping someone with more experience can elaborate on. I was using the following and receiving the error mentioned throughout this thread.

win.loadURL('file://${__dirname}/renderer/main.html')

after switching the above code to the following the error was gone, and the html would render.

win.loadURL('file://' + __dirname + '/renderer/main.html')

It seems like the original was giving an improper path to the html file for some reason, does anyone know why?

@milewski

This comment has been minimized.

milewski commented Feb 3, 2018

@s-lawrence The improper path is due to:

win.loadURL('file://${__dirname}/renderer/main.html')

Should be

win.loadURL(`file://${__dirname}/renderer/main.html`)

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

@s-lawrence

This comment has been minimized.

s-lawrence commented Feb 3, 2018

Ah ok that makes sense. Thank you @milewski for elaborating on that as well as providing a reference.

I usually stick with concatenating, but now that I know the proper syntax I’ll start using template literals more, they’re a much cleaner look.

@jakehockey10

This comment has been minimized.

jakehockey10 commented Feb 8, 2018

@milewski , I don't see a difference in your two snippets. Is the second one supposed to be different than the first one?

@rob3c

This comment has been minimized.

rob3c commented Feb 8, 2018

@jakehockey10 The second one has backticks instead of single quotes,. The backticks indicate it's a template literal rather than just a string literal. The first example is a regular string literal, so the ${__dirname} part never gets substituted with the __dirname value. It's pretty hard to notice sometimes if your editor doesn't highlight them differently (the GFM syntax highlighter doesn't distinguish them, unfortunately).

@jakehockey10

This comment has been minimized.

jakehockey10 commented Feb 8, 2018

Ah gotcha. I didn't notice that difference when viewing it in GitHub's Markdown, but I use Visual Studio Code and definitely notice the difference there as you mention. Sorry for the false alarm ;-)

unmarco added a commit to unmarco/Photon that referenced this issue May 9, 2018

@dpgraham dpgraham referenced this issue Jun 4, 2018

Closed

Installation problem on Windows 10 (64-bit) #554

0 of 2 tasks complete
@fatalmuffin

This comment has been minimized.

fatalmuffin commented Jun 14, 2018

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.

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