Reputation: 49
I'm going through this tutorial. I remade the code a little to fit it to Electron 11 according to the docs. The most important is index.js file as follows:
const { BrowserWindow } = require('electron');
const path = require('path');
const notifyBtn = document.getElementById('notifyBtn');
notifyBtn.addEventListener('click', (event) => {
const modalPath = path.join('file://', __dirname, 'add.html');
let win = new BrowserWindow({
width: 400,
height: 200,
webPreferences: {
nodeIntegration: true,
enableRemoteModule: true
}
});
win.on('close', () => { win = null });
win.loadURL(modalPath);
win.show();
});
The above code checks if button from index.html file has been clicked and creates new BrowserWindow where puts add.html content. Here's index.html code:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';" />
<link rel="stylesheet" href="../assets/css/main.css">
</head>
<body>
<div class="row">
<div id="price-container">
<p class="subtext">Current BTC USD</p>
<h1 id="price">Loading...</h1>
</div>
<div id="goal-container">
<p><img src="../assets/img/up.png" alt=""><span id="targetPrice">Choose a Target Price</span></p>
</div>
<div id="right-container">
<button id="notifyBtn">Notify me when...</button>
</div>
</div>
<script src="index.js"></script>
</body>
</html>
When the app is running and I try to click the button I get the following error in DevTools console:
Uncaught TypeError: BrowserWindow is not a constructor
at HTMLButtonElement.<anonymous>
Could you tell me please why that error occures? I'm new at Electron. Thank you in advance for all answers!
Upvotes: 0
Views: 1226
Reputation: 56
Creating a new window through a call to new BrowserWindow()
is usually done from the main process. From a renderer process, you need to make use of the remote API.
The remote module provides a simple way to do inter-process communication (IPC) between the renderer process (web page) and the main process.
In Electron, GUI-related modules (such as dialog, menu etc.) are only available in the main process, not in the renderer process. In order to use them from the renderer process, the ipc module is necessary to send inter-process messages to the main process. With the remote module, you can invoke methods of the main process object without explicitly sending inter-process messages, similar to Java's RMI.
BTW, you could have checked that BrowserWindow is indeed undefined
, therefore not a constructor, by logging its value to the DevTools console:
const { BrowserWindow } = require('electron');
console.log (BrowserWindow); // -> undefined
So, in order to get a proper BrowserWindow constructor, you must write indeed:
const { BrowserWindow } = require('electron').remote;
Upvotes: 4