Electron - Not allowed to load local resource
Asked Answered
V

17

62

Evening,
I'm looking into using electron to package an existing angular2 build. I thought I had a dry run working but the actual packaging seems to be failing (see final step below) and I want to understand why. Here's what I'm doing...

Create Project
Use angular-cli to start a new project ng new electron-ng2-cli --style=scss

Install electron and electron-builder

Edit package.json
Make the following additions...
"main": "main.js"

"build":
{
  "appId": "com.electrontest.testapp",
  "mac": {
    "category": "your.app.category.type"
  }
}

and add the following to the scripts...

"pack": "build --dir",
"dist": "build",
"electron": "electron main.js",
"postinstall": "install-app-deps"

Create main.js
I just copied the code from the electron quick start. The only change I make is to the location of index.html which I set to /dist/index.html

Amend base
In index.html change <base="/"> to <base="./">

Pack code
Run ng build. This puts all the packaged code in /dist

Test Run
Run npm run electron. This works fine. An Electron app fires up and I see the angular stuff running within it.

Create App For Distribution
Run npm run pack to create a packaged app. The packaging seems to go ok - I get a warning about a missing icon and a warning that my code is unsigned but I'm guessing they shouldn't be fatal?
The problem is that when I now run the app by double clicking in Finder I get an error in the console saying: Not allowed to load local resource: file:///Users/<username>/Documents/development/electron-ng2-cli/dist/mac/electron-ng2-cli.app/Contents/Resources/app.asar/dist/index.html


So, can anyone explain what is different between the packaged app that fails and the one that runs ok when I use npm run electron?

What can I do to fix this issue and get the app running correctly?

Thank you for making it to the end. This got longer than I wanted but I hope I explained myself ok. If you can help or give any pointers that would be great - many good vibes will be thought in your general direction :)

Cheers all

Vary answered 13/12, 2016 at 21:38 Comment(0)
V
32

It took a lot of trial and error but I got this working. There is a lot here that I don't totally understand, and much that might be pointless or bad practice and it might all fall down at the very next step but if, like me, you are just trying to get over the first hump then maybe something I found will help you.

I found the problem by unpacking the app.asar file that electron-builder produces. Instead of containing the bundled code from my dist folder it contained all the project code (*.ts *.scss etc). The problem was just that the packing functions were packing up the wrong stuff.
The steps to get the right source into the final app are simple when you lay them out but my god they didn't half put up a fight! Starting from where I left off in my initial question I did the following...

Remember that my project structure is the default one set up by angular-cli

Electron specific files
I moved the main.js down into src and changed its name to electron-main.js just to stop any confusion with the main.ts that is already in there. I also changed the path it references back to /index.html.
Next I created a new application level package.json also in src and gave it the following content:

 {
  "name": "application-name",
  "description": "CLI app",
  "author": "Me me me",
  "version": "0.0.1",
  "main": "electron-main.js"
}

angular-cli.json
I changed the outDir to build purely because electron seems to output to dist by default and I wanted some separation at this stage. Then I addded package.json and electron-main.js to the assets array.

Main package.json
I removed the "main":"main.js" as it is apparently no longer needed here. In scripts I changed the test command to electron build to point it at the build folder where the bundled code will be.
Finally, I went to the build field and added the following content:

"directories": {
  "buildResources": "build",
  "app": "build"
}

Seems pretty obvious now. This just tells the compiler where to look for the assets that will make up the final app. It was defaulting to the working directory and that was my problem.

Using this setup I can now run ng build to bundle my project into the build folder along with the electron-main.js and package.json.
This done I can run npm run electron to quickly launch a test app or npm run pack to build an app that can be launched from Finder.

Boom. Job done. I'll be back here in ten minutes with another annoying question I expect. Gotta love the dev these days :)

Vary answered 15/12, 2016 at 21:32 Comment(4)
is there another way to work around this than doing it this way?Extravascular
You give a great practice to build an electron app. But I can't find how to solve the problem 'Not allowed to load local resource' when try to load some local files. How can you fix this?Pernell
Is this still valid with most up-to-date angular? I don't know what you mean by "Finally, I went to the build field and added the following content: "directories": { "buildResources": "build", "app": "build" }"Tempting
@Vary this solution didn't work for me. I am able to generate exe with the help of electron + angular 10+ and also able to install it. But when i run the installed application it is getting blocked by trend micro antivirus, where in other system the antivirus is not installed that let me use that installed application. I have googled and tried multiple solutions but neither of worked.Prokofiev
G
81

Problem may be the invalid path in main.js, correct it if necessary

enter image description here

Germayne answered 7/8, 2018 at 19:44 Comment(5)
D'oh! That was silly... (That moment when 25 other folks did the same mistake haha)Hurry
Thanks for sharing. i'm very new to EletronJS. I tried almost all the possible way to solve this issue. But after viewing your opinion. I checked my base set up & found, I didn't put any name of my workspace. So simply put a name & edit testBuild.code.workspace and restart VS code. All done.Shang
This was my case, i had typo in my directory :)Eth
@Germayne this solution didn't work for me. I am able to generate exe with the help of electron + angular 10+ and also able to install it. But when i run the installed application it is getting blocked by trend micro antivirus, where in other system the antivirus is not installed that let me use that installed application. I have googled and tried multiple solutions but neither of worked.Prokofiev
Remember to rebuild your code after changing that, otherwise it won't workGlair
V
32

It took a lot of trial and error but I got this working. There is a lot here that I don't totally understand, and much that might be pointless or bad practice and it might all fall down at the very next step but if, like me, you are just trying to get over the first hump then maybe something I found will help you.

I found the problem by unpacking the app.asar file that electron-builder produces. Instead of containing the bundled code from my dist folder it contained all the project code (*.ts *.scss etc). The problem was just that the packing functions were packing up the wrong stuff.
The steps to get the right source into the final app are simple when you lay them out but my god they didn't half put up a fight! Starting from where I left off in my initial question I did the following...

Remember that my project structure is the default one set up by angular-cli

Electron specific files
I moved the main.js down into src and changed its name to electron-main.js just to stop any confusion with the main.ts that is already in there. I also changed the path it references back to /index.html.
Next I created a new application level package.json also in src and gave it the following content:

 {
  "name": "application-name",
  "description": "CLI app",
  "author": "Me me me",
  "version": "0.0.1",
  "main": "electron-main.js"
}

angular-cli.json
I changed the outDir to build purely because electron seems to output to dist by default and I wanted some separation at this stage. Then I addded package.json and electron-main.js to the assets array.

Main package.json
I removed the "main":"main.js" as it is apparently no longer needed here. In scripts I changed the test command to electron build to point it at the build folder where the bundled code will be.
Finally, I went to the build field and added the following content:

"directories": {
  "buildResources": "build",
  "app": "build"
}

Seems pretty obvious now. This just tells the compiler where to look for the assets that will make up the final app. It was defaulting to the working directory and that was my problem.

Using this setup I can now run ng build to bundle my project into the build folder along with the electron-main.js and package.json.
This done I can run npm run electron to quickly launch a test app or npm run pack to build an app that can be launched from Finder.

Boom. Job done. I'll be back here in ten minutes with another annoying question I expect. Gotta love the dev these days :)

Vary answered 15/12, 2016 at 21:32 Comment(4)
is there another way to work around this than doing it this way?Extravascular
You give a great practice to build an electron app. But I can't find how to solve the problem 'Not allowed to load local resource' when try to load some local files. How can you fix this?Pernell
Is this still valid with most up-to-date angular? I don't know what you mean by "Finally, I went to the build field and added the following content: "directories": { "buildResources": "build", "app": "build" }"Tempting
@Vary this solution didn't work for me. I am able to generate exe with the help of electron + angular 10+ and also able to install it. But when i run the installed application it is getting blocked by trend micro antivirus, where in other system the antivirus is not installed that let me use that installed application. I have googled and tried multiple solutions but neither of worked.Prokofiev
G
23

In case this helps anyone, the issue I was having was I had the path set using process.cwd():

win.loadURL(`file://${process.cwd()}/dist/index.html`);

Which when packaged is not correct since the the main.js file is not in the root anymore. Changing to __dirname:

win.loadURL(`file://${__dirname}/dist/index.html`);

Fixed the issue for me.

Gaea answered 1/1, 2019 at 16:29 Comment(0)
P
17

Just change the BrowserWindow' options: new BrowserWindow({ webPreferences: { webSecurity: false } }) If window's url points to a remote source, like http://..., browser will not allow to load local resource, unless you set the options above.

Pernell answered 16/3, 2018 at 10:0 Comment(4)
Turning off security is never an answerMorel
@Morel The problem is the default security options of a browser not allowed to load local resource, but Electron is not just a browser. Do you have another way?Pernell
From Electron docs: Do Not Disable WebSecurity.Tetraploid
A counter view to all the comments above: Electron is a great GUI for desktop apps, and many apps have no ability to show anything external. It's all just "my code", and so all this "security" absolutism is misplaced and unwelcome. Put another way: my code can access your whole hard drive. My code does not show web content. It has no way of running someone else's code. For apps like that, all of these "security" warnings and features add nothing but hassle.Exit
E
7

I had the same issue and my mistake was the win.loadURL was not correct (loadURL tried to load a file who doesn't exist). Be sure your url is correct otherwise you will get an error.

Egoism answered 16/4, 2019 at 12:40 Comment(0)
G
2

this works for me on linux

 newWindow.loadFile(`${__dirname}/index.html`);

you can add this to view the directory of your main.js and from there navigate to the index.html. console.log(__dirname)

Greenburg answered 14/11, 2019 at 20:37 Comment(0)
S
1

You are just missing a '.' here. You only need to put relative path instead of absolute path.

win.loadFile('./dist/index.html');
Substantialize answered 26/11, 2019 at 10:40 Comment(0)
B
1

i had the same problem and I solved it by looking for the path .
for exemple my error message is

file:///C:/Users/username/Desktop/fetni%20mohamed/electron/app/elctronapp/dist/electron-app/index.html

looking in the dist folder I found a folder named electronapp but in the path it's electron-app so by changing the folder name it worked.
you can change the output path in the angular.json, and specifiy the same name as in the path shown in the error
Burns answered 18/8, 2021 at 13:22 Comment(0)
T
1

I'm currently running Angular12+ and this simple solution worked for me:

"build": {
    //config
    "directories": {"output": "release/"},
    //more config
}

With this, the packed app with the installer is now created in release/ folder, and now I can install it. The dist/ folder remains, because that's where Angular builds the app.

Tsuda answered 20/2, 2022 at 14:54 Comment(0)
W
1

popClingwrap answer worked for me, but I wanted to keep the original project structure (keeping package.json at top level). As popClingwrap stated my app.asar file contained the not compiled files of my angular application. The content of the build folder was ignored.

So my approach look at little bit different.

I used the default project structure provided by angular cli.

angular.json I change the outputPath to "build", to avoide conflicts with the electron build dir.

"options": {
   "outputPath": "build"
}

Electron specific files

electron-main.js: I kept this file as is, at the top level of the project.

The pathname of the index.html was set to match the new build directory of angular.

mainWindow.loadURL(
  url.format({
    pathname: path.join(__dirname, `/build/index.html`)
  })
);

Main package.json The most important change was done in this file. The "file" sections copies only the needed files to the electron-builder dir.

{
  ....
  "build": {
    ....
    "files": [
      "!.angular",
      "build/**",
      "!node_modules",
      "!src",
      "electron-main.js",
      "package.json"
    ]
  }
}

This did the trick from me without changing my default project structure. Many thanks to popClingwrap who got me on the right track.

Wheaten answered 6/6, 2022 at 11:25 Comment(2)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Denounce
This was very helpful for me. In addition to this, I built my application for Mac (arm64), opened up the application (mac applications are like a folder, right-click -> Show Package Contents to see), and looked in: /Content/resources/app, which showed me what the working directory is when built. The suggestions here about build setup combined with modifying my main.js for electron to point to the correct location solved my build issues.Difficult
C
0

I had the exact problem when i tried to build my app with electron-builder...

What worked for me was in package.json file i built with ng build then runed electron-builder

"scripts": {
 ...
"build-installer": "ng build --prod && electron-builder"
},

and in the index.html changed base href to

 <base href="">
Cryptonymous answered 26/9, 2020 at 21:37 Comment(0)
A
0

By changing "private": true, to "private": false in package.json. works for me.

{
  "name": "dashboard",
  "version": "0.0.0",
  "main": "main.js",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e",
    "electron": "ng build && electron .",
    "pack":"electron-packager ."
  },
  "private": false,
  "dependencies": {
    "@angular/animations": "~10.2.0",
    "@angular/cdk": "^8.2.3",
    "@angular/common": "~10.2.0",
    "@angular/compiler": "~10.2.0",
    "@angular/core": "~10.2.0",
    "@angular/flex-layout": "^9.0.0-beta.29",
    "@angular/forms": "~10.2.0",
    "@angular/material": "^8.2.3",
    "@angular/platform-browser": "~10.2.0",
    "@angular/platform-browser-dynamic": "~10.2.0",
    "@angular/router": "~10.2.0",
    "hammerjs": "^2.0.8",
    "highcharts": "^7.2.2",
    "highcharts-angular": "^2.4.0",
    "rxjs": "~6.6.3",
    "tslib": "^1.14.1",
    "zone.js": "~0.10.3"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "^0.1002.0",
    "@angular/cli": "^10.2.0",
    "@angular/compiler-cli": "~10.2.0",
    "@angular/language-service": "~10.2.0",
    "@types/jasmine": "~3.3.8",
    "@types/jasminewd2": "~2.0.3",
    "@types/node": "~8.9.4",
    "codelyzer": "^5.0.0",
    "electron": "^10.1.5",
    "electron-packager": "^15.1.0",
    "jasmine-core": "~3.4.0",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "^5.2.3",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "~2.0.1",
    "karma-jasmine": "~2.0.1",
    "karma-jasmine-html-reporter": "^1.4.0",
    "protractor": "^7.0.0",
    "ts-node": "~7.0.0",
    "tslint": "~5.15.0",
    "typescript": "~4.0.5"
  }
}

Anemo answered 27/10, 2020 at 18:31 Comment(0)
S
0

This is can also be thrown when index.html does not exist.

In my case, my build folder "dist" was being ignored by electron-builder and not packaged properly into /app.

See this issue for more information

Scissile answered 10/12, 2021 at 20:22 Comment(0)
N
0

Adding this :

{
  "from": "../dist",
  "filter": ["**/*"]
}

into "files" section of electron-builder.json fixed the issue for me.

Naphthalene answered 4/5, 2023 at 8:25 Comment(0)
S
0

I had similar issue and by adding below code in "build" this is fixed:-

"files": [
    "**/*",
    "!**/*.ts",
    "!*.map",
    "!package.json",
    "!package-lock.json",
    {
      "from": "../dist",
      "filter": ["**/*"]
    }
],

Mainly

{
    "from": "../dist",
    "filter": ["**/*"]
}

And remove "extraResources" if present.

And in winloadurl add dist like this:-

win.loadURL(path.join(__dirname,'../dist/index.html'));

I am using Electron-24, Node-18 and Angular-16

Stimulate answered 16/6, 2023 at 14:8 Comment(0)
S
0

in my case, I was running npm run make script first ("make": "electron-forge make") before running npm build, however after I built it with "npm run build" and ran "npm run make" I was able to see my project running from exe file

Stress answered 5/3 at 13:26 Comment(0)
S
-2

I had the same problem. This worked for me

// and load the index.html of the app.
  window.loadURL(url.format({
    pathname: path.join(__dirname, 'dist/index.html'), // important
    protocol: 'file:',
    slashes: true,
    // baseUrl: 'dist'
  }));
Shouse answered 30/8, 2017 at 13:45 Comment(3)
url.format() just return an url string, makes no difference.Pernell
I have no clue. I have same doubts you have. but it worked.Shouse
This solves the problem because url.format is passing back a string how loadURL expects. The solution above using ticks instead of single quotes works, but so should this.Moray

© 2022 - 2024 — McMap. All rights reserved.