Cannot get property of undefined browser window - javascript

When running electron 13.1.X and above I get the error - menuHandler.js:8 Uncaught TypeError: Cannot read properties of undefined (reading 'getBrowserWindow').
code from main.js
const { electron, app, Notification, ipcMain } = require('electron');
var Path = require('path');
var url = require('url');
const { BrowserWindow } = require('electron');
The error occurs from menuHandler.js:8
const { remote } = require("electron");
const Window = remote.getBrowserWindow();
And so, I can't use the function:
$("#minimize").click(function() {
Window.minimize();
});
Here it throws an error passing the above message, meanwhile it works fine on older versions of electron. Please how can I fix this?

Remote was removed from the main electron package, you have to install #electron/remote on your project.
To use this new electron remote add this to your main file:
require('#electron/remote/main').initialize();
const { BrowserWindow } = require('electron');
const window = new Browser window();
require("#electron/remote/main").enable(window.webContents);
On your renderer:
const { BrowserWindow } = require('#electron/remote');
Readme of the new remote module: https://github.com/electron/remote#migrating-from-remote

Related

require module inside preload script in electron

I'm building an app with electron react and MySQL, I'm stuck in preload script where i want to make my db instance available in render-er process, i got the following error
Error: module not found: ./config/db in console.
this happening when i try to require a module inside preload script.
const { app, BrowserWindow } = require("electron");
const path = require("path");
const isDev = require("electron-is-dev");
const dotenv = require("dotenv");
//load .env
dotenv.config();
function createWindow() {
// Create the browser window.
const mainWindow = new BrowserWindow({
title: "Electron",
minWidth: 800,
minHeight: 600,
webPreferences: {
preload: path.join(__dirname, "preload.js"),
devTools: isDev,
},
});
//get url dependig on envirement (dev/prod)
const url = isDev
? `http://localhost:${process.env.PORT}/`
: `file://${path.join(__dirname, "../../dist/react/index.html")}`;
// load the url
mainWindow.loadURL(url);
// Open the DevTools.
isDev && 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.whenReady().then(() => {
createWindow();
app.on("activate", function () {
// On macOS 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();
});
});
// 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", function () {
if (process.platform !== "darwin") app.quit();
});
// 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 require them here.
require("./handlers");
preload
const { contextBridge, ipcRenderer } = require("electron");
const { db } = require("./config/db");
contextBridge.exposeInMainWorld("mainApi", {
db,
});
Since Electron v20.0.0, the sandbox parameter defaults to true (according to the list of Breaking Changes)
One of the side effects of the sandbox attribute is that it can only require a few things:
A require function similar to Node's require module is exposed, but can only import a subset of Electron and Node's built-in modules:
electron (only renderer process modules)
events
timers
url
To disable sandboxing, just add sandbox: false to your webPreferences on window creation:
// ...
// Create the browser window.
const mainWindow = new BrowserWindow({
title: "Electron",
minWidth: 800,
minHeight: 600,
webPreferences: {
preload: path.join(__dirname, "preload.js"),
devTools: isDev,
sandbox: false, // fixes require() in preloader
},
});
// ...

How to import Menu in Electron 15

I need to import Menu for my render.js file. But either Remote is undefined or I get some error.
With the following code I get this error:
Uncaught TypeError: Cannot read properties of undefined (reading 'members')
I also tried something from the Electron Documentation using the .enable(webContents) method, but I cannot get it working either.
What's the way of doing this?
Index.js:
const { app, BrowserWindow } = 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 = () => {
// Create the browser window.
const mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true,
contextIsolation: false,
}
});
render.js:
const { desktopCapturer } = require('electron');
const { Menu } = require('#electron/remote')
console.log(Menu);
As read in the npm #electron/remote doc
#electron/remote/main must be initialized in the main process before it can be used from the renderer:
// in the main process:
require('#electron/remote/main').initialize()
I actually fixed this.
First:
You need to add these lines in the index.js file:
const remote = require('#electron/remote/main');
remote.initialize()
Then, also in the index.js file, inside the createWindow() function you need to include this:
remote.enable(mainWindow.webContents);
In the render.js file to import menu:
const remote = require('#electron/remote')
const { Menu } = remote;
Check my GitHub repo where I have the files if this didn't work.
The render.js file is: https://github.com/Auax/electron-screen-recorder/blob/main/src/render.js
The index.js file is: https://github.com/Auax/electron-screen-recorder/blob/main/src/index.js

Getting TypeError: "path" is not defined: undefined while executing serial port program for windows using JavaScript

I am trying to execute a Serial Port program for windows based application using JavaScript and Arduino Uno. This is the link i referred https://channel9.msdn.com/Blogs/raw-tech/Arduino-talks-back-to-Nodejs-Drama-on-the-Serial-Port. While i try to execute the program by issuing npm start COMxx. Iam getting the following error.
App threw an error during load
TypeError: "path" is not defined: undefined
at new SerialPort (C:\serial test js\serial-app\node_modules\#serialport\stream\lib\index.js:116:11)
at Object.<anonymous> (C:\serial test js\serial-app\src\index.js:7:16)
at Module._compile (internal/modules/cjs/loader.js:1078:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1108:10)
at Module.load (internal/modules/cjs/loader.js:935:32)
at Module._load (internal/modules/cjs/loader.js:776:14)
at Function.f._load (electron/js2c/asar_bundle.js:5:12684)
at loadApplicationPackage (C:\serial test js\serial-app\node_modules\electron\dist\resources\default_app.asar\main.js:110:16)
at Object.<anonymous> (C:\serial test js\serial-app\node_modules\electron\dist\resources\default_app.asar\main.js:222:9)
at Module._compile (internal/modules/cjs/loader.js:1078:30)
And this is my code
const { app, BrowserWindow } = require('electron');
const path = require('path');
const SerialPort = require('serialport');
const Readline = SerialPort.parsers.Readline;
const portname = process.argv[2];
const myPort = new SerialPort(portname, {
baudRate:9600,
parser: new Readline("\n")
});
myPort.on('open',onOpen);
myPort.on('data',onData);
// Handle creating/removing shortcuts on Windows when installing/uninstalling.
if (require('electron-squirrel-startup')) { // eslint-disable-line global-require
app.quit();
}
const createWindow = () => {
// Create the browser window.
const mainWindow = new BrowserWindow({
width: 800,
height: 600,
});
// and load the index.html of the app.
mainWindow.loadFile(path.join(__dirname, 'index.html'));
// Open the DevTools.
mainWindow.webContents.openDevTools();
};
function onOpen(){
console.log("Open Connection");
}
function onData(data){
console.log("on Data "+data);
}
// 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', createWindow);
// 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.
Help me to resolve the issue
Instead :
const myPort = new SerialPort(portname, {
baudRate:9600,
parser: new Readline("\n")
});
Try this :
const myPort = new SerialPort({
path:portname,
baudRate:9600,
parser: new Readline("\n")
});
As path is a part of nodejs core module, it doesn't need to be listed explicitly
const path = require('path');
Just try to stop your solution and re-run application it should be working.

Why can't you read package.json in a builded electron app?

Hello Stackoverflow users!
I am trying to place all of the configuration for the electron app in the package.json file.
Here is my code snippet:
index.js
const { app, BrowserWindow, ipcMain } = require('electron');
const fs = require('fs');
function readConf() {
const data = fs.readFileSync('./package.json', 'utf8');
return data;
}
ipcMain.on('synchronous-message', (event, arg) => {
event.returnValue = readConfig();
})
index.html
<script type="text/javascript">
const { ipcRenderer } = require('electron')
config = JSON.parse(ipcRenderer.sendSync('synchronous-message', ''))
</script>
<h1>Version of <script>document.write(config.name)</script> is <script>document.write(config.version);</script></h1>
The code is working when you run the app via npm start, but when you make it into an exe with electron-forge and squirrel (npm make) and try to run it after installing it throws an error that the package.json file can't be found.
So what do you need to specify as the path to the file to read it in the built app?
I am using electron forge.
I found a way to fix the issue!
Instead of
const data = fs.readFileSync('./package.json', 'utf8');
You'll need to write
const data = fs.readFileSync(__dirname + '/../package.json', 'utf8');

Engine not found for the ".js" file extension

I want to use koa-views with Koa and Koa-Router with Next.js. In previous projects, I had no issues with express but in this project, I have to use Koa. Using its router, I want to render a page: /some/page/:id. Following the same Nextjs way:
router.get('/some/page/:id', async (ctx, next) => {
const actualPage = '/some/page/id' // id.js (not actual name 😝)
await ctx.render(actualPage, {/* could pass object */})
});
That would work if I was using express. With Koa:
const Koa = require('koa');
const views = require('koa-views');
// const render = require('koa-views-render'); <-- I what's this?
[..] // Making things short here
const server = new Koa();
const router = new Router();
// My issue, I'm seeing tutorials using other engines: .ejs etc
// I'm not using any, I only have .js files
server.use(views(__dirname + "/pages", { extension: 'js' }));
Using the same router.get... function as above, I get:
Error: Engine not found for the ".js" file extension
When I go to /some/page/123, I'd expect it to render the file /pages/some/page/id.js. How?
It turns out I do not need any extra modules to achieve this 🙀
Create a function called, ie, routes then pass app and router as a param
const routes = (router, app) => {
router.get('/some/page/:id', async (ctx) => {
const { id } = ctx.params
const actualPage = '/some/page/id'
// Render the page
await app.render(ctx.req, ctx.res, actualPage, {foo: 'Bar'})
}
}
module.exports = routes
Inside your server.js file:
// const routes = require('./routes);
// const app = next({ dev }); // import other modules for this section
// app.prepare().then(() => {
// const router = new Router();
// [..]
// routes(router, app)
// })
The commented out section is a slim down version to make a point in where things should be.

Categories

Resources