1
votes

I do not get the desired output when running the following electron app i.e alert box containing pwd as output. However, the commented line inside index.html seems to work fine. The developer console of the chromium window says "Uncaught ReferenceError: __dirname is not defined at HTMLButtonElement.<anonymous>". This snippet is taken verbatim(except the commented line) from the book "Electron in action" by Steve Kinney 2019 edition.

any suggestions?

package.json is as follows

{
  "name": "bookmarker",
  "version": "1.0.0",
  "description": "electron app",
  "main": "./app/main.js",
  "scripts": {
    "start": "electron .",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Wasim Aftab",
  "license": "ISC",
  "dependencies": {
    "electron": "^9.0.0"
  }
}

main.js is as follows

const {app, BrowserWindow} = require('electron');
let mainWindow = null;
app.on ('ready', () => {
    console.log('Hello, from electron');
    mainWindow = new BrowserWindow();
    mainWindow.webContents.loadFile(__dirname + '/index.html');
});

index.html is as follows

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <meta http-equiv="Content-Security-Policy" content="
default-src 'self';
script-src 'self' 'unsafe-inline';
connect-src *">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>Bookmarker</title>
</head>

<body>
    <h1>Hello from Electron</h1>
    <p>
        <button class="alert">Current Directory</button>
    </p>
</body>
<script>
    const button = document.querySelector('.alert');
    button.addEventListener('click', () => {
        alert(__dirname);
        // alert(window.location.pathname.replace(/[^\\\/]*$/, ''));
    });
</script>

</html>
1
what are you trying to achieve with alert(__dirname);? also __dirname wont be what your expecting once packaged, instead use app.getAppPath, or app.getPath github.com/electron/electron/blob/master/docs/api/… - Lawrence Cherone

1 Answers

2
votes

__dirname is a nodejs concept, it does not exist in the browser.

One way to resolve the issue is to set nodeIntegration to true:

mainWindow = new BrowserWindow({
    webPreferences: {
        nodeIntegration: true
    }
});

Another way would be to use a preload script (nodeIntegration is always enabled for preload scripts):

mainWindow = new BrowserWindow({
    webPreferences: {
        preload: (__dirname + "/preload.js")
    }
});

And then in the preload.js file:

window.__dirname = __dirname