cannot read property 'request' of undefined in electron - electron

When I try to use net.request, it returns an error "cannot read property 'request' of undefined in electron".
This is my code for main.js
const electron = require('electron');
const {app, Menu} = electron;
const {BrowserWindow} = require('electron');
var mainWindow = null;
app.on('ready', function(){
mainWindow = new BrowserWindow({
width: 500,
height: 300
});
mainWindow.loadURL('file://' + __dirname + '/index.html');
mainWindow.openDevTools();
mainWindow.setMenu(null);
mainWindow.on('closed', function () {
mainWindow = null;
});
const {net} = require('electron');
const request = net.request('https://github.com');
request.on('response', (response) => {
console.log('STATUS: ${response.statusCode}')
console.log('HEADERS: ${JSON.stringify(response.headers)}');
response.on('data', (chunk) => {
console.log('BODY: ${chunk}');
});
response.on('end', () => {
console.log('No more data in response.');
});
});
request.end();
});
I couldn’t find what went wrong. Can any suggest a solution for this? any help will be appreciated

It doesn't throw me error on 1.4.5
[Highlight of comment:]
Also, based on the release notes, net api is available only from 1.4.5 on https://github.com/electron/electron/releases/tag/v1.4.5

Related

require cannot be used in Electron's preloadjs

main.js
//...
const win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
preload: path.join(__dirname, './preload/preload.js')
}
});
//...
preload.js
const { contextBridge, ipcRenderer } = require('electron');
const qrcode = require('qrcode');
contextBridge.exposeInMainWorld('electronAPI', {
qrc: qrcode
})
the error
Unable to load preload script: F:\project\bluetools\preload\preload.js
Error: module not found: qrcode
Although direct exposure is not a good behavior, but I need to do it; and the example in the official documentation can be exposed directly, although it is not recommended; but why I require any third-party package in preloadjs shows "module not found: xxx"
Just add nodeIntegration: true to webPreferences. Like that.
//...
const win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true,
preload: path.join(__dirname, './preload/preload.js')
}
});
//...
I refer to here, I have got a solution, but it seems to be more troublesome, but what is this compared to security and normative?
ipc.js
module.exports = {
xxx_req: (argements) => {
const { ipcMain, winb: win } = argements;
ipcMain.on('xxx_req', (event, response) => {
win.webContents.send("xxx", "hello");
});
}
}
main.js
const ipcm = require('./ipc.js');
const createWindow = () => {
const win = new BrowserWindow({...});
ipcm.xxx_req({ ipcMain, winb: win })
}
preload.js
const { contextBridge, ipcRenderer } = require('electron');
contextBridge.exposeInMainWorld('electronAPI', {
xxx_req: (response) => ipcRenderer.send('xxx_req',response),
xxx: (callback) => ipcRenderer.on('xxx',callback),
})
index.js(render process)
window.electronAPI.xxx_req("hello");
window.electronAPI.qrcode((event, detail) => {
console.log(detail)
});
If you still don't understand why I did this, please refer to here.

app.browserWindow returns TypeError during testing of electron app with Spectron

I am trying to run simple tests on my electron application using Spectron and mocha. However, whenever I try to use the browserWindow API I obtain an error of the form:
TypeError: Cannot read property '.....' of undefined
I did a bit of research on the internet. Some proposed solutions I found were to ensure nodeIntegration is set to true, and that DevTools is not open on the application window. I have ensured that both these criteria are satisfied, but I am still receiving the same error. What am I missing here? I am attaching my code for reference.
main.js
const {app, BrowserWindow} = require('electron')
const path = require('path')
let mainWindow
function createWindow () {
mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
nodeIntegration:true
}
})
mainWindow.loadFile('index.html')
}
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()
})
test.js
const Application = require('spectron').Application
const assert = require('assert')
const electronPath = require('electron')
const path = require('path')
const { app } = require('electron')
const { expect } = require('chai')
describe('Application launch', function () {
this.timeout(10000)
before(function () {
this.app = new Application({
path: electronPath,
args: [path.join(__dirname, '.')]
})
return this.app.start()
})
after(function () {
if (this.app && this.app.isRunning()) {
return this.app.stop()
}
})
it('should be a focused window', function(){
return this.app.client.waitUntilWindowLoaded().browserWindow.isFocused().then(res => {
expect(res).to.be.true
})
})
})
The issue arises at the line this.app.client.waitUntilWindowLoaded().browserWindow.isFocused()

Why did electron not create file?

I'm building an app on electron and now I'm trying to create a simple file.
Here's the JS:
const app = require("electron").remote;
var dialog = app.dialog;
var fs = require("fs");
document.getElementById('save_project').onclick=() => {
dialog.showSaveDialog((filename) => {
if(filename === undefined){
console.log("You didnt save the file");
return;
};
var content = "hello there";
fs.writeFile(filename, content, (err) => {
if(err) console.log(err);
alert("The file has been successfully saved.")
})
});
};
This window will open as supposed:
Then, I wrote for instance: "hello.txt" on the name input and clicked save.
There's no log written on the console neither a file written in the directory
Edit:
with this js, happens the same ():
const fs = require("fs");
const {dialog} = require("electron").remote;
document.getElementById("save_project").addEventListener("click", () => {
dialog.showSaveDialog((filename) => {
if(filename === undefined){
console.log("nop");
return;
}
fs.writeFile(filename, content, (err) => {
if(err){
console.log(err);
return;
}
alert("file created");
});
});
}, false);
Edited:
Here's the createWindow()
function createWindow () {
// Create the browser window.
const mainWindow = new BrowserWindow({
width: 1920,
height: 1080,
webPreferences: {
preload: path.join(__dirname, "preload.js"),
nodeIntegration: true
},
});
const childWindow = new BrowserWindow ({ width: 1600, height: 800, parent: mainWindow, modal: true, show : false});
// and load the index.html of the app.
mainWindow.loadFile("index.html");
childWindow.loadFile("welcome.html");
childWindow.once("ready-to-show", () => {
childWindow.show();
});
// Open the DevTools.
mainWindow.webContents.openDevTools();
}
Basically, from what i understood, "dialog.showSaveDialog((filename).." this was kinda blocking... i fixed by using:
const {dialog} = require("electron").remote;
let filename = dialog.showSaveDialogSync()
if(filename === undefined){
console.log("filename undefined");
return;
}else{
console.log(filename)
saveAsToFile(filename, ...);
}

Why Electron-Angular project gives the GL ERROR while build

My Project is built on Angular-7 & Electron-6. The OS of my pc is Ubuntu-18.04. When I build the project it's showing the error bellow. The code snippet is bellow:
main.js:
const { app, BrowserWindow } = require('electron');
let win;
function createWindow() {
win = new BrowserWindow({
x: 0,
y: 0,
width: 1200,
height: 800,
});
win.loadFile(`./dist/smartPharmacyErp/index.html`);
win.on('closed', () => {
win = null
})
};
app.on('ready', createWindow);
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') { app.quit() }
});
app.on('activate', () => {
if (win === null) { createWindow() }
});
The errors are:
GL ERROR :GL_INVALID_OPERATION : glBufferData: <- error from previous GL command
Failed to load module script: The server responded with a non-JavaScript MIME type of "". Strict MIME type checking is enforced for module scripts per HTML spec.

Opening new Window - Electron

I'm currently trying to implement a new Window on my Electron App.
So I want to include a button, and when you click on this Button, a new Window should be opened.
I didn't find anything in the Electron documentation, maybe one of you can help me.
Perhaps something like this:
const button = document.getElementById('<your_button_id>');
button.addEventListener('click', () => {
createBrowserWindow();
});
function createBrowserWindow() {
const remote = require('electron').remote;
const BrowserWindow = remote.BrowserWindow;
const win = new BrowserWindow({
height: 600,
width: 800
});
win.loadURL('<url>');
}
I believe the answer that has been taken as correct is outdated.
I have managed to do it with the ipc module and with the solution given by Nishkal.
Please, read the ipc module, I'm new to electron and not very experienced with programming. I'm sure you can come with better solutions.
Code I added in order for it to work:
my main.js
const {app, BrowserWindow} = require('electron');
const path = require('path');
//ipc
const { ipcMain } = require('electron')
ipcMain.on('asynchronous-message', (event, arg) => {
createWindow();
})
const createWindow = () => {
const win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
},
});
win.loadFile('index.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();
})
my preload.js
window.addEventListener('DOMContentLoaded', () => {
const { ipcRenderer } = require('electron')
ipcRenderer.on('asynchronous-reply', (event, arg) => {
console.log(arg) // prints "pong"
})
//button and its event listener
const b1 = document.getElementById('b1');
b1.addEventListener('click', () => {
ipcRenderer.send('asynchronous-message', 'ping')
})
})
To open a window from the renderer:
window.open("https://github.com", "_blank", "top=500,left=200,frame=false,nodeIntegration=no");
https://www.electronjs.org/docs/latest/api/window-open

Resources