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.
Related
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.
I have no idea what's going on, to be honest.
I've been keeping an eye to the icon and it just vanishes after a few minutes. No, it does not go to the arrow near the clock:
This is my icon showing up (the explosion in red):
I don't know how to debug if the icon is there but empty or if there's an event triggering it to hide, or if the tray process closes itself because of a bug. Nothing happens in the console or my app.
Could someone please help? Below is my whole index.js:
const {app, BrowserWindow, Tray, Menu} = require('electron');
const path = require('path');
var win = '',
iconpath = path.join(__dirname, '/libs/img/icon.ico');
// Create the browser window
function createWindow () {
// BrowserWindow size
win = new BrowserWindow({
width: 800,
height: 720,
webPreferences: {
nodeIntegration: true
}
});
// tray menu
var contextMenu = Menu.buildFromTemplate([
{
label: 'Show app', click: function () {
win.show()
}
},
{
label: 'Quit', click: function () {
app.isQuiting = true;
app.quit();
}
}
]);
// Creates tray menu with tray icon
var appIcon = new Tray(iconpath);
// Define menu
appIcon.setContextMenu(contextMenu);
win.on('close', function () {
app.isQuiting = true;
app.quit();
});
// Load the index.html of the app
win.loadFile('./view/index.html');
}
app.on('ready', createWindow);
This is a well-known problem related to garbage collection, mentioned in the Electron FAQ page:
My app's window/tray disappeared after a few minutes.
So, a quick fix is to move up the declaration of the appIcon variable out of the createWindow function, next to the win variable for instance:
const {app, BrowserWindow, Tray, Menu} = require('electron');
const path = require('path');
var win = '',
appIcon = null,
iconpath = path.join(__dirname, '/libs/img/icon.ico');
// Create the browser window
function createWindow () {
// BrowserWindow size
win = new BrowserWindow({
width: 800,
height: 720,
webPreferences: {
nodeIntegration: true
}
});
// tray menu
var contextMenu = Menu.buildFromTemplate([
{
label: 'Show app', click: function () {
win.show()
}
},
{
label: 'Quit', click: function () {
app.isQuiting = true;
app.quit();
}
}
]);
// Creates tray menu with tray icon
appIcon = new Tray(iconpath);
// Define menu
appIcon.setContextMenu(contextMenu);
win.on('close', function () {
app.isQuiting = true;
app.quit();
});
// Load the index.html of the app
win.loadFile('./view/index.html');
}
app.on('ready', createWindow);
I was having the same problem, but I got the solution for this.
This happens when your tray variable which is used to store the tray gets garbage collected.
You can get rid of this just by making the variable global.
In your case create appIcon variable out of the createWindow function like this:
let appIcon = null;
and then assign tray object like this:
appIcon = new Tray(iconpath);
ref: https://www.electronjs.org/docs/faq#my-apps-tray-disappeared-after-a-few-minutes
I'd like to have one single Electron window, split in two parts:
the left part is a BrowserWindow loading https://gmail.com
the right part is another BrowserWindow loading Gmail too, but I'd like these two browsers to be "independent", i.e. the cookies/LocalStorage/etc. should be independent (like if we have a normal Chrome window vs. a incognito window) ; thus allowing to have one Gmail account on left / another account connected on the right part
some other UI buttons on top of the single Electron window.
This code works, but it creates 2 windows instead of one:
const { app, BrowserWindow } = require('electron')
const path = require('path')
app.once('ready', () => {
let win = new BrowserWindow({show: false})
win.once('show', () => { win.webContents.executeJavaScript('validateFlights()') })
win.loadURL('https://www.gmail.com')
win.show()
let win2 = new BrowserWindow({show: false})
win2.once('show', () => { win.webContents.executeJavaScript('validateFlights()') })
win2.loadURL('https://www.gmail.com')
win2.show()
})
How to have them in one window?
A little late, but to add two browsers within one window you have to use BrowserWindow.addBrowserView instead of BrowserWindow.setBrowserView. You'll get the following:
const { BrowserView, BrowserWindow, app } = require('electron')
function twoViews () {
const win = new BrowserWindow({ width: 800, height: 600 })
const view = new BrowserView()
win.addBrowserView(view)
view.setBounds({ x: 0, y: 0, width: 400, height: 300 })
view.webContents.loadURL('https://electronjs.org')
const secondView = new BrowserView()
win.addBrowserView(secondView)
secondView.setBounds({ x: 400, y: 0, width: 400, height: 300 })
secondView.webContents.loadURL('https://electronjs.org')
app.on('window-all-closed', () => {
win.removeBrowserView(secondView)
win.removeBrowserView(view)
app.quit()
})
}
app.whenReady().then(twoViews)
Once you create two BrowserView objects, you just add them to the window. You'll also want to remove the views when tearing down the application. If you don't you might get a segmentation fault.
What you are looking for is BrowserView
From the docs:
A BrowserView can be used to embed additional web content into a BrowserWindow. It is like a child window, except that it is positioned relative to its owning window. It is meant to be an alternative to the webview tag.
It looks like this is what you want, the views can render separate HTML pages and position them relatively inside the same browser window.
// In the main process.
const { BrowserView, BrowserWindow } = require('electron')
let win = new BrowserWindow({ width: 800, height: 600 })
win.on('closed', () => {
win = null
})
let view = new BrowserView({
webPreferences: {
nodeIntegration: false
}
})
win.setBrowserView(view)
view.setBounds({ x: 0, y: 0, width: 300, height: 300 })
view.webContents.loadURL('https://electronjs.org')
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.
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.