DenverCoder9
DenverCoder9

Reputation: 1179

Electron Looking for Resources in Root Folder

We are building a web app (in Angular 2, although I am not sure if that is the reason for my issue) that we also need to run as an Electron application. I have branched out the solution and replaced items in the package.json so that on start it launches Electron. For reasons that I don't understand, in our solution it is looking for relative paths of resources in the root folder of my drive, not the folder that the app was launched from (C:\Source\NameOfMyApp).

Can someone explain why this may occur?

Changes to package.json

{
    "main": "electron-main.js",
    "scripts": {
        "start": "electron ."
    }
},
"devDependencies": {
    "electron-prebuilt": "^1.2.0"
}

When I run npm start, the index.html runs but it cannot find any resources.

Code in index.html

<link rel="stylesheet" href="test.css">

Where test.css is a file that does exist in the same folder as index.html

Code in electron-main.js

const app = electron.app;
const BrowserWindow = electron.BrowserWindow;

let mainWindow;
function createWindow() {

    mainWindow = new BrowserWindow({ width: 1200, height: 900 });
    console.log("__dirname", __dirname);

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

    // Open the DevTools.
    mainWindow.webContents.openDevTools();

    mainWindow.on('closed',
        function() {
            mainWindow = null;
        });
}

app.on('ready', createWindow);

DevTools console error

The error message in the DevTools Console

My understanding is that it should look for files in the same folder that the app was created from, not from the root, but Electron for whatever reason is assuming all relative links are from the root C:/ level.

Upvotes: 2

Views: 9630

Answers (2)

adamci
adamci

Reputation: 49

If you want your app to use relative paths both in the browser and in Electron, you need to specify a relative root by adding the following to your index.html:

<base href="./">

Upvotes: 3

Poul Kruijt
Poul Kruijt

Reputation: 71961

Do you have <base href="/" > in your index.html? I believe electron uses the filesystem and / is the root of filesystem, so C:\.

You should change your <base href="/"> to the path where your index.html resides

<base href="C:/path/to/index">

Upvotes: 2

Related Questions