Reputation: 319
I'm trying to learn ElectronJS right now from the book "Electron in Action" (https://www.amazon.com/Electron-Action-Steve-Kinney/dp/1617294144/
).
The bit of code I'm having difficulty with is one in which I am, through JS code within <script>
tags in the HTML file loaded into a Renderer Process window, trying to access the __dirname
variable (which is normally only available in node but in Electron, is supposed to be available to the Chromium context too).
For anybody interested, it's Listing 2.8 (page : 28). Here is the code:
<!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>
<script>
const button = document.querySelector('.alert');
button.addEventListener('click', ()=> {alert(__dirname);});
</script>
</body>
</html>
And this is the code for the Main process:
const {app, BrowserWindow} = require('electron');
let main_window = null;
app.on('ready',
() =>
{
console.log('Hello from Electron');
main_window = new BrowserWindow();
main_window.webContents.loadFile('app/index.html');
}
);
But it doesn't work. In the developer console of the Rendering Window, each time I click the button, the error spawns which says that __dirname
is not defined.
I enclose below a screenshot of the Error Message:
How do I resolve this issue? Thanks in advance.
Upvotes: 0
Views: 1715
Reputation: 41
This is probably NOT RECOMMENDED for production apps but if you must, then, in addition to
nodeIntegration:true
add
contextIsolation: false
so that your BrowserWindow constructor looks like this:
mainWindow = new BrowserWindow({
webPreferences: {
nodeIntegration:true,
contextIsolation: false
}
});
See solution here
Read more on Context Isolation here
Note, that the way this is done at the moment, is by using Preload Scripts (video).
and then, to learn more about the history of Electron security see here
Upvotes: 0
Reputation: 3305
in main.js while you create a window set nodeIntegration
to true
mainWindow = new BrowserWindow({
width: 600,
height: 300,
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
nodeIntegration:true
}
})
Upvotes: 2