Red Virus Red Virus - 2 months ago 26
Node.js Question

Cannot load local file

Just started today learning Node.js + Electron. I' am having difficlties in figuring out what's wrong with the following code.

In the console I' am getting the following error

Not allowed to load local resource: file://%24%7B__dirname%7D/index.html


Here's the code am working with currently

const electron = require('electron')
const {app, BrowserWindow} = electron

app.on('ready', function(){
let win = new BrowserWindow({
width: 600,
height: 500
})
win.loadURL('file://${__dirname}/index.html')
win.webContents.openDevTools()
})

Answer

It looks like you're trying to use ES2015 functionality to print the URL. This needs backticks instead of normal quotes:

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

Or you could just use normal string concatonation:

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

More Detailed Explanation

To expand on this, ES2015 (or ES6), is an updated specification for JavaScript which has been adopted by modern browsers and Node versions. It adds some functionality for including variables in Strings, which could be called 'Template Strings'. It allows you to instantiate a String with backticks (instead of single or double quotes) and allows you to drop variables into those strings delimited by a dollar sign and curly braces. It is designed to make String concatenation easier and more verbose.

What you are doing in your code is using the dollar sign and curly braces, but not instantiating the String appropriately to make use of that functionality.

See more here.

Comments