Parent process crashes when opening two or more child windows - javascript

I have a problem, the following code (simple as it looks) does not allow me to open more than three windows (not counting the parent). The children work correctly, but the father crashes and doesn't let me continue. What I can do?
ipcMain.on('openNewWindow', function(event, arg) {
windowEEE = new BrowserWindow({
center: true,
width: 1024,
height: 720,
minWidth: 1024,
minHeight: 720,
// show: false,
icon: __dirname + '/resources/iconos/support.png',
webPreferences: {
nodeIntegration: true, // is default value after Electron v5
contextIsolation: false, // protect against prototype pollution
enableRemoteModule: true // turn off remote
}
})
// windowEEE.setResizable(true);
// windowEEE.setMenuBarVisibility(false)
// windowEEE.once('ready-to-show', () => {
// windowEEE.show()
// })
windowEEE.loadFile(arg.html, {query: arg.query})
});
The logical thing is to open as many windows as one would like without any limit, but for some reason electronjs is hanging the parent process.
the function of call to ipcMain is
var openClient = (id) =>{
ipcRenderer.sendSync('openNewWindow', {
html:"./elements/components/equipo.html",
query: { id : id }
})
}

Ok, sorry for asking. But the answer is that the ipc function had no return. Adding to it, event.returnValue = true worked.

Related

How to add a delay for splash screen in electron

I want the splash screen to stay on the screen for 3 seconds but electron loads the application way faster than that and so it stays on for barely a split second.
I'm using Angular to make the SPA.
This is the electron function for the splashscreen and the main window
app.on("ready", () => {
// create main browser window
mainWindow = new BrowserWindow({
titleBarStyle: "hidden",
width: 1920,
height: 1080,
show: false, // don't show the main window
});
// create a new `splash`-Window
splash = new BrowserWindow({
width: 800,
height: 450,
transparent: true,
frame: false,
alwaysOnTop: true,
});
splash.loadURL(`file://${__dirname}/splash.html`);
mainWindow.loadURL(`file://${__dirname}/dist/MedalFrontEnd/index.html`);
// if main window is ready to show, then destroy the splash window and show up the main window
function showFunc() {
mainWindow.once("ready-to-show", () => {
splash.destroy();
mainWindow.show();
});
}
showFunc();
});
You can use setTimeout in your function to wait for 3 seconds. Something like below should work -
function showFunc() {
mainWindow.once("ready-to-show", () => {
setTimeout(function(){
splash.destroy();
mainWindow.show();
}, 3000);
});
}

How to use electron-positioner

There is no explicit example of how to position your ELECTRON JS app to a specific area. The only syntax is available on GitHub, and it does not describe it well.
It's quite straight forward. Consider this code that positions the mainWindow once the ready event fires. You should be able to drop in the 'ready' event below to demonstrate the positioner.
// load the module
const Positioner = require('electron-positioner');
let mainWindow = null;
// create the main window
async function createWindow () {
mainWindow = new BrowserWindow({
height: 420,
width: 600,
x: 0, // default position left
y: 0, // default position top
show: false,
webPreferences: {
nodeIntegration: true,
preload: path.join(__dirname, 'node_modules', 'electron', 'dist', 'electron-bridge.js')
}
});
// reposition after creating the window.
app.on('ready', async () => {
await createWindow();
let positioner = new Positioner(mainWindow);
positioner.move('bottomRight');
});
Of course this affect may be achieved with the x and y values via the BrowserWindow constructor, but it is quite handy to have canned positions provided by the module.

Electron reactjs app show empty page after reloading if user navigate to other route

I create my project with create-react-app. I use react-router-dom for router and electron-builder to package my app.
When I first run my application, it works normally but once I reload the page all becomes white. If I don't navigate to other routes, the app still works after reloading.
Below is my electron/index.js code
function createWindow() {
mainWindow = new BrowserWindow({
width: 1280,
height: 600,
minWidth: 800,
minHeight: 200,
autoHideMenuBar: true,
useContentSize: true,
resizable: true,
webPreferences: {
nodeIntegration: true,
},
});
mainWindow.loadURL(isDev
? 'http://localhost:3000'
: `file://${path.join(__dirname, '../build/index.html')}`);
mainWindow.focus();
mainWindow.on('close', (e) => {
if (willQuitApp) {
/* the user tried to quit the app */
mainWindow = null;
} else {
/* the user only tried to close the window */
e.preventDefault();
mainWindow.hide();
}
});
}
app.on('ready', createWindow);
I found the answer. I only need to use <HashRouter> instead of <BrowserRouter>
You got empty page after reloading because when you navigate to another page, you change the url. So when you reload, electron will load that url instead of index.html file

Electron "require is not defined"

I'm making an application which I need to give access to the file system (fs) module, however even with nodeIntegration enabled the renderer gives me this error:
Uncaught ReferenceError: require is not defined
All similar problems I could find had a solution that said they needed to turn nodeIntegration on, however I already have it enabled.
This is my main.js:
const electron = require('electron');
const {app, BrowserWindow} = electron;
let win;
app.on('ready', () => {
var { width, height } = electron.screen.getPrimaryDisplay().workAreaSize;
width = 1600;
height = 900;
win = new BrowserWindow({'minHeight': 850, 'minWidth': 1600, width, height, webPreferences: {
contextIsolation: true,
webSecurity: true,
nodeIntegration: true
}});
win.setMenu(null);
win.loadFile('index.html');
win.webContents.openDevTools()
});
My index.js, linked in index.html as <script src="index.js"></script> currently only has require("fs"); in it, I've commented out all the other stuff.
I don't know why require still doesn't work even though nodeIntegration is enabled.
When you have nodeIntegration disabled but aren't using contextIsolation, you could use a preload script to expose a safe version of it on the global object. (Note: you shouldn't expose the entire fs module to a remote page!)
Here's an example of using a preload script in this way:
// main process script
const mainWindow = new BrowserWindow({
webPreferences: {
contextIsolation: false,
nodeIntegration: false,
preload: './preload.js'
}
})
mainWindow.loadURL('my-safe-file.html')
// preload.js
const { readFileSync } = require('fs')
// the host page will have access to `window.readConfig`,
// but not direct access to `readFileSync`
window.readConfig = function () {
const data = readFileSync('./config.json')
return data
}
// renderer.js
const config = window.readConfig()
If you're only loading local pages, and those pages don't load or execute unsafe dynamic content then you might reconsider the use of contextIsolation for this strategy. If you want to keep contextIsolation on, however (and you definitely should if you have a chance of showing unsafe content), you can only communicate with the preload script with message passing via postMessage.
Here's an example of the same scenario above, but with contextIsolation on and using message passing.
// main process script
const mainWindow = new BrowserWindow({
webPreferences: {
contextIsolation: true,
nodeIntegration: false,
preload: './preload.js'
}
})
mainWindow.loadURL('my-unsafe-file.html')
// preload.js
const { readFileSync } = require('fs')
const readConfig = function () {
const data = readFileSync('./config.json')
return data
}
window.addEventListener('message', (event) => {
if (event.source !== window) return
if (event.data.type === 'request') {
window.postMessage({ type: 'response', content: readConfig() })
}
})
// renderer.js
window.addEventListener('message', (event) => {
if (event.source !== window) return
if (event.data.type === 'response') {
const config = event.data.content
}
})
window.postMessage('request')
While this is definitely more verbose and difficult to deal with (and forces things to be async, because message passing is async), it's also much more secure. A pair of small JS wrappers around the postMessage API could make this easier to work with (e.g. via an RPC-like mechanism), but remember that the whole point of using contextIsolation is because you can't trust the renderer, so your preload script shouldn't trust just any message it gets via the postMessage API — you should always verify the event that you receive to ensure that you trust it.
This slide deck describers in detail why turning off Node integration without using context isolation is not always a good idea.

Communicating between two renderer processes in Electron

I am writing an Eletron program. In the program there is one index-window which is created by the main process (main.js). In this window there is a list of files (images). When I click on one of the files in that list I want to start a second window that displays that file.
That second window is started by the renderer process of the index-window (index.js). How can I communicate between the renderer process of the index-window and the renderer process of the second window?
Code:
Creating the index-window from the main process in main.js:
let win;
function createWindow(){
// Create the browser window.
win = new BrowserWindow({width: 1024, height: 768, minWidth: 800, minHeight: 600, show: false, icon: 'files/images/icon.png'});
win.loadURL(`file://${__dirname}/files/html/index.html`);
win.once('ready-to-show', () => {
win.show()
})
// Emitted when the window is closed.
win.on('closed', () => {
win = null;
});
}
app.on('ready', createWindow);
In the index.html index.js (renderer process) is started:
<script src="../javascript/index.js"></script>
In index.js the function create_sprite_window() is called which creates a child window:
const fs = require('fs');
const path = require('path');
const {BrowserWindow} = require('electron').remote
let child_windows = [];
function create_child_window(URL, width, height){
let rem_win = require('electron').remote.getCurrentWindow();
let new_win = new BrowserWindow({width: width, height: height, minWidth: 400, minHeight: 300, show: false, parent: rem_win, minimizable: true, maximizable: true, skipTaskbar: true});
child_windows[child_windows.length] = new_win;
console.log(child_windows);
new_win.loadURL(URL);
new_win.once('ready-to-show', () => {
new_win.show()
})
return new_win;
}
function create_sprite_window(){
new_win = create_child_window(`file://${__dirname}/../html/sprite_manager.html`, 800, 400);
}
The child windows are stored in the array child_windows.
Is it possible to then send the path of the image to the second window or, alternatively, edit the <img> tag of the second window (setting the source of the <img> tag in the second window to the image with getElementById.src = path;) from the index-window?.
I have found the answer by myself.
To show the correct image in the second renderer window, I add a GET parameter to the URL which contains the path of the image.

Categories

Resources