Electronjs - BrowserWindow is not a constructor error inside renderer process - javascript

Node version: 14.18.0
OS: Mac
This is my package.json file
{
"name": "cryptic-app",
"version": "1.0.0",
"description": "",
"main": "main.js",
"scripts": {
"start": "electron ./main.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"electron": "14.1.0"
}
}
This is my main.js
const electron = require('electron')
const path = require('path')
const shell = require('electron').shell
const { app, BrowserWindow, Menu } = electron
function createWindow () {
const mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
enableRemoteModule: true,
nodeIntegration: true,
contextIsolation: false,
}
})
// and load the index.html of the app.
const indexFilePath = path.join( __dirname, 'src/index.html')
mainWindow.loadFile(indexFilePath)
mainWindow.webContents.openDevTools()
var menu = Menu.buildFromTemplate([
{
label: 'Menu',
submenu: [
{
label: 'Adjust notification value'
},
{
label: 'CoinMarketCap',
click() {
shell.openExternal('http://www.coinmarketcap.com/')
}
},
{
type: 'separator'
},
{
label: 'Exit',
click() {
app.quit()
}
},
]
}
])
Menu.setApplicationMenu(menu)
}
app.whenReady().then(() => {
createWindow()
app.on('activate', function () {
if (BrowserWindow.getAllWindows().length === 0) createWindow()
})
})
app.on('window-all-closed', function () {
if (process.platform !== 'darwin') app.quit()
})
This is my index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Hello World!</title>
<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="https://s3.amazonaws.com/coursetro/tutorial_images/up.svg">
<span id="target-price">Choose a target price</span>
</p>
</div>
<div class="right-container">
<button id="notifyBtn">Notify me when...</button>
</div>
</div>
<script src="./index.js"></script>
</body>
</html>
This is my index.js file
const electron = require('electron')
const path = require('path')
const { BrowserWindow } = electron
console.log(electron)
const notifyBtn = document.getElementById('notifyBtn')
notifyBtn.addEventListener('click', function(e) {
const modalPath = path.join('file://', __dirname, 'add.html')
console.log("modalPath", modalPath)
let win = new BrowserWindow({ width: 400, height: 200, parent: top })
win.on('close', function() {
win = null
})
win.loadFile(modalPath)
win.show()
})
This is the electron object from index.js
I am getting BrowserWindow is not a constructor error inside the render process, I am not sure what is causing this issue. Can someone please help?

This is how I solved this problem :-
As I am using electron > 14, so remote resources are not available inside renderer process and not made avaolable by lectron module.
To make remote resources available to renderer process I added this module. #electron/remote
Then this is how my main.js looks now
const remote = require('#electron/remote/main')
const electron = require('electron')
remote.initialize() // Intitialize
const path = require('path')
const shell = require('electron').shell
const { app, BrowserWindow, Menu } = electron
function createWindow () {
// Create the browser window.
const mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true,
contextIsolation: false,
show: false,
}
})
remote.enable(mainWindow.webContents) // Loads webcontents
const indexFilePath = path.join( __dirname, 'src/index.html')
mainWindow.loadFile(indexFilePath)
mainWindow.webContents.openDevTools()
var menu = Menu.buildFromTemplate([
{
label: 'Menu',
submenu: [
{
label: 'Adjust notification value'
},
{
label: 'CoinMarketCap',
click() {
shell.openExternal('http://www.coinmarketcap.com/')
}
},
{
type: 'separator'
},
{
label: 'Exit',
click() {
app.quit()
}
},
]
}
])
Menu.setApplicationMenu(menu)
}
app.whenReady().then(() => {
createWindow()
app.on('activate', function () {
if (BrowserWindow.getAllWindows().length === 0) createWindow()
})
})
app.on('window-all-closed', function () {
if (process.platform !== 'darwin') app.quit()
})
Now I can can access Browser window inside my index.js file like this
const { BrowserWindow } = require('#electron/remote')
Links to refer for:-
About webcontents, read here

Related

electron-devtools-installer not working react

I'm currently starting a new project with electron and react and I don't understand but I'm trying to use React devTools, I've tried some methods and none of them worked.
For instance, I followed here the method of electron-devtools-installer, which can be found here : https://github.com/MarshallOfSound/electron-devtools-installer
and when I launch the app the inspector still tells me
that
Download the React DevTools for a better development experience: https://reactjs.org/link/react-devtoolsYou might need to use a local HTTP server (instead of file://): https://reactjs.org/link/react-devtools-faq
Here is my main.js :
const { app, BrowserWindow, Notification, ipcMain } = require("electron");
const path = require("path");
const isDev = !app.isPackaged;
const {
default: installExtension,
REACT_DEVELOPER_TOOLS,
} = require("electron-devtools-installer");
let createWindow = () => {
const win = new BrowserWindow({
width: 800,
height: 600,
backgroundColor: "white",
title: "TaleSmith",
icon: path.join(__dirname, "../assets/icons/appIcon.png"),
webPreferences: {
nodeIntegration: false,
worldSafeExecuteJavaScript: true,
contextIsolation: true, // is a feature that ensures that both your preload scripts and Electron internal logical tun in separate context
preload: path.join(__dirname, "preload.js"),
},
});
win.loadFile(path.join(__dirname, "..", "src", "index.html"));
isDev && win.webContents.openDevTools();
};
if (isDev) {
require("electron-reload")(__dirname, {
electron: path.join(
__dirname,
"..",
"..",
"node_modules",
".bin",
"electron",
),
});
}
app.whenReady().then(async () => {
installExtension(REACT_DEVELOPER_TOOLS)
.then((name) => console.log(`Added Extension: ${name}`))
.catch((err) => console.log("An error occurred: ", err));
createWindow();
});
ipcMain.on("notify", (_, message) => {
new Notification({
title: "Hello World",
body: message,
}).show();
});
app.on("window-all-closed", () => {
if (process.platform !== "darwin") {
app.quit();
}
});
app.on("activate", () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow();
}
});
Thanks a lot for your help !
Leverage the "dom-ready" event to initiate the dev tools instead of when the app is ready. Give this a try
const {
app,
BrowserWindow,
Notification,
ipcMain
} = require("electron");
const path = require("path");
const isDev = !app.isPackaged;
const {
default: installExtension,
REACT_DEVELOPER_TOOLS,
} = require("electron-devtools-installer");
let createWindow = () => {
const win = new BrowserWindow({
width: 800,
height: 600,
backgroundColor: "white",
title: "TaleSmith",
icon: path.join(__dirname, "../assets/icons/appIcon.png"),
webPreferences: {
nodeIntegration: false,
worldSafeExecuteJavaScript: true,
contextIsolation: true, // is a feature that ensures that both your preload scripts and Electron internal logical tun in separate context
preload: path.join(__dirname, "preload.js"),
},
});
win.loadFile(path.join(__dirname, "..", "src", "index.html"));
if (isDev) {
require("electron-reload")(__dirname, {
electron: path.join(
__dirname,
"..",
"..",
"node_modules",
".bin",
"electron",
),
});
// Errors are thrown if the dev tools are opened
// before the DOM is ready
win.webContents.once("dom-ready", async () => {
await installExtension([REACT_DEVELOPER_TOOLS])
.then((name) => console.log(`Added Extension: ${name}`))
.catch((err) => console.log("An error occurred: ", err))
.finally(() => {
win.webContents.openDevTools();
});
});
}
};
app.on("ready", createWindow);
ipcMain.on("notify", (_, message) => {
new Notification({
title: "Hello World",
body: message,
}).show();
});
app.on("window-all-closed", () => {
if (process.platform !== "darwin") {
app.quit();
}
});
app.on("activate", () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow();
}
});

I want close electron app from another html page with button

We are currently improve a project with electronjs: We have main.js for electron as you know and we have another html page that javascripts codes in it. We created a close button in this html page and this button should close the app but we cant reach main.js for close the app. Can you help me?
This code is from html page :
<div class="background-three link-container">
<button class="link-three" onclick="kapat()" id="kptbtn">Kapat</button>
</div>
<script>
function kapat(){
//what should I write here.
}
</script>
and this main.js
const { app, BrowserWindow } = require('electron')
const path = require('path')
function createWindow() {
const win = new BrowserWindow({
transparent: true,
frame: false,
resizable: false,
width: 500,
height: 700,
webPreferences: {
preload: path.join(__dirname, 'preload.js')
}
})
win.loadFile('girisEkrani.html')
}
app.whenReady().then(() => {
createWindow()
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow()
}
})
})
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit()
}
})
You must use ipcMain and ipcRenderer. Main for reading message and Renderer for sending message.
.html page
<script>
function kapat() {
const { ipcRenderer } = require('electron')
const ipc = ipcRenderer;
ipc.send('kapat');
}
...
</script>
if you define ipc stuff out of the function it will not work and effect other functions.
main.js
const { app, BrowserWindow, ipcMain } = require('electron')
const path = require('path')
const ipc = ipcMain;
function createWindow() {
const win = new BrowserWindow({
transparent: true,
frame: false,
resizable: false,
width: 500,
height: 700,
webPreferences: {
nodeIntegration: true,
contextIsolation: false,
}
})
ipc.on('kapat', () => { win.close() })
win.loadFile('girisEkrani.html')
}

Electron - How to pass data to renderer from a new opened window?

I'm struggling to pass a data from newly opened site window to renderer. What I want to achieve is to find a login button on site and listen on click event. I was reading about webview in electron, but I couldn't make It work. For now I'm stuck on window.open() method. Can you please point me what aspect I am missing? Here are my files:
//main.js
const {app, BrowserWindow, ipcMain} = require('electron')
const path = require('path')
function createWindow () {
const mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
nodeIntegration: true,
contextIsolation: false,
enableRemoteModule: true
}
})
mainWindow.loadFile('index.html')
// Open the DevTools.
mainWindow.webContents.openDevTools()
}
app.whenReady().then(() => {
createWindow()
app.on('activate', function () {
if (BrowserWindow.getAllWindows().length === 0) createWindow()
})
})
app.on('window-all-closed', function () {
if (process.platform !== 'darwin') app.quit()
})
ipcMain.on("open-login-window", () => {
console.info('dostal');
});
//renderer.js
const electron = require("electron");
const ipc = electron.ipcRenderer
const button = document.getElementById("login-button");
button.addEventListener("click", () => {
ipc.send("open-login-window")
const windowProxy = window.open('https://www.somesite.com/login', null, 'minimizable=false')
windowProxy.postMessage('hi', '*')
});

Function in Electron does not work but in Node does

I'm running the same function from both Electron and Node, but obtaining different results:
Invoking the function using Node from command line works fine, I get the list of connected devices:
node my_func.js
var iosDevice = require("node-ios-device");
iosDevice.devices(function (err, devices) {
if (err) {
console.error("Error!", err);
} else {
console.log(devices);
}
});
But putting the same chunk of code in main.js in Electron
(it's not in any other renderer file and it is just invoked from command line using the standard: $ npm run start),
yields the following outcome:
main.js
const { app, BrowserWindow } = require("electron");
var iosDevice = require("node-ios-device");
iosDevice.devices(function (err, devices) {
if (err) {
console.error("Error!", err);
} else {
console.log(devices);
}
});
// SET ENVIRONTMENT
process.env.NODE_ENV = "development";
// process.env.NODE_ENV = "production";
const isDev = process.env.NODE_ENV !== "production" ? true : false;
// CHECK PLATFORM
const isMac = process.platform === "darwin" ? true : false;
let mainWindow;
function createMainWindow() {
mainWindow = new BrowserWindow({
title: "test",
width: 700,
height: 195,
icon: "./assets/icons/Icon_256x256.png",
resizable: isDev ? true : false,
backgroundColor: "white",
show: false,
webPreferences: {
nodeIntegration: true,
// sandbox: true,
// contextIsolation: false,
},
});
mainWindow.loadFile("./app/index.html");
mainWindow.webContents.on("did-finish-load", function () {
mainWindow.show();
});
}
app.on("ready", () => {
createMainWindow();
});
app.on("window-all-closed", () => {
if (!isMac) {
app.quit();
}
});
app.on("activate", () => {
if (BrowserWindow.getAllWindows().length === 0) {
createMainWindow();
}
});
The console does not show any result
Apparently, three instances of the app get created, 3 app icons pops up in Dock:
Three app icons show up
this is the package.json
{
"name": "test",
"version": "1.0.0",
"description": "",
"main": "main.js",
"scripts": {
"start": "electron ."
},
"author": "Viking",
"license": "ISC",
"devDependencies": {
"electron": "^11.4.4"
},
"dependencies": {
"node-ios-device": "^1.9.2"
}
}
and requiring the npm "node-ios-device" package does not present any issue.
Any idea about how I can accomplish the same task using Electron instead Node?
Thank you.
UPDATE
After trying difference things this is the most close I got to a solution:
I moved the function to another file and I call it from the main.js file spawning a child process and invoking the function using node:
ipcMain.on("dev:getinfo", (event, options) => {
let child_proc;
let devices;
child_proc = spawn("node", ["device.js"]);
child_proc.stdout.on("data", (data) => {
devices = `${data}`;
});
child_proc.on("exit", function (code, signal) {
console.log(devices);
});
});
And it works, in development...
but I have the feeling that it's not going to work in production since the users I'd like to distribute this app do not have Node.js installed and I don't know how I could bundle electron in such way that the users don't need to have Node.js installed.
So an issue was resolved but another one showed up 😐
Further info about my comment above...
If you want to get access to the iOSdevices from the main process to the renderer (that is the electron frontend or the webpage), try to use the
webContents or the ipcMain/ipcRenderer event emitters.
// In the main process.
const { app, BrowserWindow } = require("electron");
const { iosDevice } = require("node-ios-device");
-- previous snips --
let win = null
app.whenReady().then(() => {
win = new BrowserWindow({ width: 800, height: 600 })
win.loadURL(`file://${__dirname}/index.html`)
win.webContents.on('did-finish-load', () => {
let devices = iosDevice.devices(function (err, devices) {
if (err) {
console.error("Error!", err);
} else {
console.log(devices);
return devices;
}
});
win.webContents.send('send-devices', devices);
})
})
Then in your index.html..
<!-- index.html -->
<html>
<body>
<script>
require('electron').ipcRenderer.on('send-devices', (event, message) => {
console.log(message) // Prints the devices
})
</script>
</body>
</html>
// https://www.electronjs.org/docs/api/web-contents#contentssendchannel-args

How to import ipcRenderer in react?

I've tried to import ipcRenderer in react app
import {ipcRenderer} from 'electron';
but I get this error message : require is not defined
You'll want to follow the steps I outline in this comment. These steps ensure security in your electron app.
main.js
const {
app,
BrowserWindow,
ipcMain
} = require("electron");
const path = require("path");
const fs = require("fs");
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let win;
async function createWindow() {
// Create the browser window.
win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: false, // is default value after Electron v5
contextIsolation: true, // protect against prototype pollution
enableRemoteModule: false, // turn off remote
preload: path.join(__dirname, "preload.js") // use a preload script
}
});
// Load app
win.loadFile(path.join(__dirname, "dist/index.html"));
// rest of code..
}
app.on("ready", createWindow);
ipcMain.on("toMain", (event, args) => {
fs.readFile("path/to/file", (error, data) => {
// Do something with file contents
// Send result back to renderer process
win.webContents.send("fromMain", responseObj);
});
});
preload.js
const {
contextBridge,
ipcRenderer
} = require("electron");
// Expose protected methods that allow the renderer process to use
// the ipcRenderer without exposing the entire object
contextBridge.exposeInMainWorld(
"api", {
send: (channel, data) => {
// whitelist channels
let validChannels = ["toMain"];
if (validChannels.includes(channel)) {
ipcRenderer.send(channel, data);
}
},
receive: (channel, func) => {
let validChannels = ["fromMain"];
if (validChannels.includes(channel)) {
// Deliberately strip event as it includes `sender`
ipcRenderer.on(channel, (event, ...args) => fn(...args));
}
}
}
);
index.html
<!doctype html>
<html lang="en-US">
<head>
<meta charset="utf-8"/>
<title>Title</title>
</head>
<body>
<script>
window.api.receive("fromMain", (data) => {
console.log(`Received ${data} from main process`);
});
window.api.send("toMain", "some data");
</script>
</body>
</html>
You need to use
const { ipcRenderer } = window.require("electron");
Otherwise it will try to import it from Webpack or whatever module bundler you use.
You can checkout this thread for a better explanation:
https://github.com/electron/electron/issues/7300
if you are looking to quickly try IPC in electron in a react component, this may help.
main.js
const {ipcMain} = require('electron')
ipcMain.on('asynchronous-message', (event, arg) => {
console.log("heyyyy",arg) // prints "heyyyy ping"
})
App.js
import React from 'react';
import './App.css';
const { ipcRenderer } = window.require('electron');
function App() {
return (
<div className="App">
<button onClick={()=>{
ipcRenderer.send('asynchronous-message', 'ping')
}}>Com</button>
</div>
);
}
export default App;
Output:
Don't forget to re-run the app after making the changes.
No preload.js added, Did not change anything in webpack config, No extra configurations.
By using contextBridge we can resolve this issue
new BrowserWindow({
width: 1200,
height: 800,
backgroundColor: "white",
webPreferences: {
nodeIntegration: false,
worldSafeExecuteJavaScript: true,
contextIsolation: true,
preload: path.join(__dirname, 'preload.js')
}
})
//example to display notification
ipcMain.on('notify', (_, message) => {
new Notification({title: 'Notification', body: message}).show();
})
preload.js
const { ipcRenderer, contextBridge } = require('electron');
contextBridge.exposeInMainWorld('electron', {
notificationApi: {
sendNotification(message) {
ipcRenderer.send('notify', message);
}
}
})
then using the below code in your reactjs component will trigger a native notification message
electron
.notificationApi
.sendNotification('My custom message!');
Below is the code worked for using electron-forge with react with preload script which exposes ipcRenderer API to renderer process in electron with webpack preload(FYI check package.json code below) option. Follow the link to create a project for electron-forge with react.
main.js
const { app, BrowserWindow, ipcMain, Notification } = require("electron");
const path = require("path");
// Handle creating/removing shortcuts on Windows when installing/uninstalling.
if (require("electron-squirrel-startup")) {
// eslint-disable-line global-require
app.quit();
}
const createWindow = () => {
console.log(__dirname, "testing");
// Create the browser window.
const mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: false,
contextIsolation: true,
worldSafeExecuteJavaScript: true,
preload: MAIN_WINDOW_PRELOAD_WEBPACK_ENTRY,
},
});
// and load the index.html of the app.
mainWindow.loadURL(MAIN_WINDOW_WEBPACK_ENTRY);
// Open the DevTools.
mainWindow.webContents.openDevTools();
};
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on("ready", () => {
console.log("/n demo", __dirname, "/n");
createWindow();
});
ipcMain.on("notify", (_, message) => {
new Notification({ title: "Notification", body: message }).show();
});
// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on("window-all-closed", () => {
if (process.platform !== "darwin") {
app.quit();
}
});
app.on("activate", () => {
// On OS X it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (BrowserWindow.getAllWindows().length === 0) {
createWindow();
}
});
// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and import them here.
package.json
{
"name": "webex-ui",
"productName": "webex-ui",
"version": "1.0.0",
"description": "My Electron application description",
"main": ".webpack/main",
"scripts": {
"start": "electron-forge start",
"package": "electron-forge package",
"make": "electron-forge make",
"publish": "electron-forge publish",
"lint": "echo \"No linting configured\""
},
"keywords": [],
"author": {
"name": "Sathishkumar R",
"email": "rsathishtechit#gmail.com"
},
"license": "MIT",
"config": {
"forge": {
"packagerConfig": {},
"makers": [
{
"name": "#electron-forge/maker-squirrel",
"config": {
"name": "webex_ui"
}
},
{
"name": "#electron-forge/maker-zip",
"platforms": [
"darwin"
]
},
{
"name": "#electron-forge/maker-deb",
"config": {}
},
{
"name": "#electron-forge/maker-rpm",
"config": {}
}
],
"plugins": [
[
"#electron-forge/plugin-webpack",
{
"mainConfig": "./webpack.main.config.js",
"renderer": {
"config": "./webpack.renderer.config.js",
"entryPoints": [
{
"html": "./src/index.html",
"js": "./src/renderer.js",
"name": "main_window",
"preload": {
"js": "./src/preload.js"
}
}
]
}
}
]
]
}
},
"devDependencies": {
"#babel/core": "^7.14.8",
"#babel/preset-react": "^7.14.5",
"#electron-forge/cli": "^6.0.0-beta.58",
"#electron-forge/maker-deb": "^6.0.0-beta.58",
"#electron-forge/maker-rpm": "^6.0.0-beta.58",
"#electron-forge/maker-squirrel": "^6.0.0-beta.58",
"#electron-forge/maker-zip": "^6.0.0-beta.58",
"#electron-forge/plugin-webpack": "6.0.0-beta.58",
"#vercel/webpack-asset-relocator-loader": "1.6.0",
"babel-loader": "^8.2.2",
"css-loader": "^6.0.0",
"electron": "13.1.7",
"node-loader": "^2.0.0",
"style-loader": "^3.0.0"
},
"dependencies": {
"electron-squirrel-startup": "^1.0.0",
"react": "^17.0.2",
"react-dom": "^17.0.2"
}
}
app.jsx
import * as React from "react";
import * as ReactDOM from "react-dom";
class App extends React.Component {
componentDidMount() {
electron.notificationApi.sendNotification("My custom message!");
}
render() {
return <h1>contextBridge</h1>;
}
}
ReactDOM.render(<App />, document.body);
preload.js
const { ipcRenderer, contextBridge } = require("electron");
contextBridge.exposeInMainWorld("electron", {
notificationApi: {
sendNotification(message) {
ipcRenderer.send("notify", message);
},
},
batteryApi: {},
fileApi: {},
});
renderer.js
import "./index.css";
import "./app";
console.log(
'👋 This message is being logged by "renderer.js", included via webpack'
);
Also, add below in webpack.rules.js
//to avoid explicit mention of jsx when importing react components
resolve: {
extensions: [".js", ".jsx"],
},
Thanks to this page
const {ipcRenderer} = require('electron')

Categories

Resources