Electron loading animation - node.js

Could someone please help me to implement a loading animation for my Electron app ?
I am learning this new technology and it would be nice to understand the correct way to do that.
I am thinking about something like :
app.on('ready', () => {
// show main content
})
app.on('not-ready', () => {
// show loading animation
})

As far as I know there is no event emitted from app before ready (only exception is will-finish-launching available only on macOS).
Furthermore, you cannot open any BrowserWindow before app is ready, so you should really wait it.
However, if your main application window loading very slow, you can still open a "loading window" before that and switch them when your main window is ready.
const { app, BrowserWindow } = require('electron')
app.on('ready', () => {
let main = null
let loading = new BrowserWindow({show: false, frame: false})
loading.once('show', () => {
main = new BrowserWindow({show: false})
main.webContents.once('dom-ready', () => {
console.log('main loaded')
main.show()
loading.hide()
loading.close()
})
// long loading html
main.loadURL('http://spacecrafts3d.org')
})
loading.loadURL('loding.html')
loading.show()
})
You can use win.on('ready-to-show') instead of win.webContents.on('dom-ready') everywhere if you want to eliminate visual flash (but losing some speed)
window.open()
If you want to do the same for BrowserWindow opened in renderer process by window.open(), you can use new-window event of webContents if nativeWindowOpen is true
main = new BrowserWindow({
webPreferences: {
nativeWindowOpen: true
}
})
main.webContents.on('new-window', (event, url) => {
// there are more args not used here
event.preventDefault()
const win = new BrowserWindow({show: false})
win.webContents.once('dom-ready', () => {
win.show()
loading.hide() // don't destroy in this case
})
win.loadURL(url)
loading.show()
event.newGuest = win
})

It can be done by displaying a new BrowserWindow displaying the activity loader , until the main app fully loads .
Let's define a createWindow funtion (as given in docs) which is responsible for loading the main app for the user as :
var loadingwindow = null; // Responsible for creating activity loader
function createWindow () {
const win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true
}
})
win.loadFile('index.html')
loadingwindow.hide() // Used to hide the loading screen when the contents in main app are loaded
}
Now , in order to display the loadingwindow screen , we need to place it in app.on('ready' , callback_fn) as shows here :
app.on("ready" , () => {
loadingwindow = new BrowserWindow({
frame : false,
movable : false,
})
loadingwindow.loadFile('activity.html') // To load the activity loader html file
loadingwindow.show();
})
That's it ! ,
To check if it is working properly , wrap the setTimeout function over the app.whenReady().then(createWindow)

Related

Kaspersky marks my Electron app as a Trojan

I recently made an Electron app that is essentially a web browser and it has 3 windows and they all get destroyed when the user closes them, leaving no excess process behind this is the only complex part of the app but Kaspersky flags it as a Trojan.
my index.js
const { app, BrowserWindow, ipcMain, desktopCapturer } = require('electron');
const path = require('path');
app.commandLine.appendSwitch("disable-http-cache");
// Handle creating/removing shortcuts on Windows when installing/uninstalling.
// eslint-disable-next-line global-require
if (require('electron-squirrel-startup')) {
app.quit();
}
function createMacroWindow(macroUrl) {
let macroWindow = new BrowserWindow({
width:800,
height:500,
frame:false,
show:false,
icon: path.join(__dirname, "./assets/icons/icon.png"),
webPreferences:{
devTools: false,
webviewTag: true,
nodeIntegration: true,
contextIsolation: false
}
})
macroWindow.loadFile(path.join(__dirname, './windows/macro-window.html'));
macroWindow.webContents.on('did-finish-load', () => {
macroWindow.webContents.send("loadURL", macroUrl)
})
macroWindow.center();
macroWindow.openDevTools();
macroWindow.show();
macroWindow.on("close", () => {
macroWindow = null;
})
require("#electron/remote/main").enable(macroWindow.webContents);
}
const createWindow = () => {
// Create the browser window.
const mainWindow = new BrowserWindow({
width: 1000,
height: 700,
frame:false,
show:false,
icon: path.join(__dirname, "./assets/icons/icon.png"),
webPreferences: {
webviewTag: true,
nodeIntegration: true,
devTools: true, // Geliştirici konsolunu kökten kısıtlayan kod (bu olmazsa CTRL+SHIFT+I yapınca yine açılır)
contextIsolation: false,
},
});
let splashScreen = new BrowserWindow({
width:1000,
height:700,
frame:false,
icon: path.join(__dirname, "./assets/icons/icon.png"),
webPreferences: {
devTools:false
}
})
// and load the index.html of the app.
mainWindow.loadFile(path.join(__dirname, 'index.html'));
splashScreen.loadFile(path.join(__dirname, './windows/splash-window.html'));
splashScreen.center();
function destroySplashScreen() {
splashScreen.close();
splashScreen = null;
}
mainWindow.webContents.on('did-finish-load', function() {
mainWindow.show();
mainWindow.maximize();
splashScreen.isDestroyed() ? console.log("splash screen already destroyed") : destroySplashScreen();
});
require('#electron/remote/main').initialize()
require("#electron/remote/main").enable(mainWindow.webContents)
ipcMain.handle(
'DESKTOP_CAPTURER_GET_SOURCES',
(event, opts) => desktopCapturer.getSources(opts)
)
let macroUrl;
ipcMain.on("openMacroWindow", (e, urlToLoad) => {
macroUrl = urlToLoad;
createMacroWindow(macroUrl);
})
ipcMain.on("closeApp", () => {
BrowserWindow.getAllWindows().forEach(window => window.close());
})
ipcMain.on('clearCache', () => {
mainWindow.webContents.session.clearStorageData([], function (data) {
console.log(data);
})
mainWindow.webContents.session.clearCache();
})
mainWindow.on("close", () => {
app.quit();
})
// Open the DevTools.
// mainWindow.webContents.openDevTools(); // Geliştirici konsolunu kapatmak için bu satırı silebilirsiniz
};
// 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);
// app.disableHardwareAcceleration()
// 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.
splashScreen is the window that opens while the mainWindow loads, it closes when the main loads and is set to null afterwards just like the macroWindow.
macroWindow is opened when the ipcMain is told to openMacroWindow
Fix
I downgraded to electron-forge version 5.2.4 from 6.x version, this fixed my issue but this is not an ideal solution.

Preload script not loading in electron react

I'm building an app with React and Electron and trying to create a communication channel between the main (electron.js in my case) and renderer processes. By achieving this, I want to access the Store object created in my main process to save user preferences etc.
I have set up a preload script and provided the path in my main.js (electron.js). But when I try to access the method defined in the preload.js from the renderer like this window.electronAPI.sendData('user-data', this.state), it does not recognise the electronAPI (undefined variable electronAPI). Also the console.log in my preload.js is never shown when a window is loaded. Hence I assume the preload script never gets loaded and I don't know why. Any help is very much appreciated!
EDIT: The preload script seems to load now because the console.log gets printed. Maybe preload.js did load before too but I could not see it since I could only access the application by opening localhost:3000 in the browser. Now the app opens in a BrowserWindow. However the 'electronAPI' defined in the preload script cannot be accessed still.
Here is the code:
electron.js (main.js)
const electron = require('electron');
const path = require('path');
const {app, BrowserWindow, Menu, ipcMain} = electron;
let isDev = process.env.APP_DEV ? (process.env.APP_DEV.trim() === "true") : false;
function createWindow (){
const win = new BrowserWindow({
width: 970,
height: 600,
backgroundColor: '#0C0456',
webPreferences: {
nodeIntegration: true,
contextIsolation: true,
enableRemoteModule: false,
preload: path.join(__dirname, 'preload.js')
}
});
//if in development mode, load window from localhost:3000 otherwise build from index.html
try {
win.webContents.loadURL(isDev
? 'http://localhost:3000'
: `file://${path.join(__dirname,'../build/index.html')}`
)
} catch(e){
console.error(e)
}
win.webContents.openDevTools({"mode":"detach"});
//Remove menu
Menu.setApplicationMenu(null);
win.once('ready-to-show', () => win.show());
console.log("main window is shown");
console.log(typeof path.join(__dirname, 'preload.js'));
win.on('crashed',() => {
console.error(`The renderer process has crashed.`);
})
}
app.on( 'ready', () => {
createWindow(); // open default window
} );
ipcMain.on('user-data', (event, args)=>{
console.log(args);
});
preload.js
const {contextBridge, ipcRenderer} = require("electron");
const validChannels = ['user-data'];
console.log("this is the preload script");
contextBridge.exposeInMainWorld('electronAPI', {
sendData: (channel, data) => {
if(validChannels.includes(channel)){
ipcRenderer.send(channel, data);
}
}
})

Electron.js | Remove new window frame

I'm using an index.html including an iframe. When a page is opened in a new tab with CTRL + Click keys, the properties I defined for BrowserWindow are not applied.
I want to remove the frame of the opened new tab. How can I do it?
const path = require('path')
const {app, BrowserWindow, Menu} = require('electron')
function createWindow() {
const win = new BrowserWindow({
width: 1000,
height: 700,
frame: false,
show: false,
})
win.loadFile('index.html')
win.once('ready-to-show', () => { win.show() });
}
const menu = Menu.buildFromTemplate([])
Menu.setApplicationMenu(menu)
app.whenReady().then(() => { createWindow() })
Windows opened via links don't inherit their parents options, instead, you have to register a window open handler and set the options manually:
win.webContents.setWindowOpenHandler(({ url }) => {
return {
action: 'allow',
overrideBrowserWindowOptions: { // These options will be applied to the new BrowserWindow
frame: false,
// other BrowserWindow settings
}
}
}
On the documentation: https://www.electronjs.org/docs/latest/api/window-open#native-window-example

Electron: can't access main.js from another .js file

I have all my html handlers in a second file (b.js). They look like this:
window.onload = function () {
let btn = window.getElementById('btn');
button.addEventListener('click', fn);
}
This works fine, but I want to make a button to open another window, so I tried adding an exported method in main.js. My full main.js is below:
const {app, BrowserWindow} = require('electron');
let mainWindow;
function createWindow () {
// Create the browser window.
mainWindow = new BrowserWindow({
width: 500,
height: 300,
frame: false,
transparent: true,
resizable: false,
webPreferences: {
nodeIntegration: true,
}
});
mainWindow.setResizable(false);
mainWindow.loadFile('index.html');
mainWindow.webContents.openDevTools();
mainWindow.on('closed', function () {
// Dereference the window object, usually you would store windows
// in an array if your app supports multi windows, this is the time
// when you should delete the corresponding element.
mainWindow.quit();
})
}
app.on('ready', createWindow);
module.exports = {
openMainScreen: function () {
mainWindow.loadFile("mainScreen.html");
mainWindow.resizeTo(1200, 800);
}
};
If I try to require(main.js)in b.js as I thought I should: I get this error:
Uncaught TypeError: Cannot read property 'on' of undefined
Pointing to app.on('ready'.... Looking at this post: Cannot read property 'on' of undefined in electron javascript It says the app is starting twice. How can I resolve this?
The way I fixed this was to use electrons built in IPCmain to communicate between javascript that was being rendered with the html and the main javascript that ran the app.
https://electronjs.org/docs/api/ipc-main

electron prevent multiple instance with middle click

I am tying to make single instance Electron application.
I am using app.makeSingleInstance , see my sample below.
SingleInstance issue with middle click :
Single Instance works if I click on app.exe 2nd time
It does not work if I middle click on a link inside my app
What I need:
Make electron app singleInstance and ensure it remaisn single instance even with middle click.
I dont want to compeltey disable middle click in my app as at some places, I have a use case for them on non-link items
How to reproduce:
use repo: https://github.com/electron/electron-quick-start
replace existing with my index.html and main.js , see below
npm install and then npm start
index.html:
<!DOCTYPE html>
<html>
<head><meta charset="UTF-8"><title>Hello World!</title></head>
<body>
<h1>app.makeSingleInstance()</h1>
Middle Click on it
</body>
</html>
main.js
const electron = require('electron')
const app = electron.app
const BrowserWindow = electron.BrowserWindow
const path = require('path')
const url = require('url')
let mainWindow
const isSecondInstance = app.makeSingleInstance((commandLine, workingDirectory) => {
if (myWindow) {
if (myWindow.isMinimized()) myWindow.restore()
myWindow.focus()
}
})
if (isSecondInstance) {
app.quit()
}
function createWindow () {
mainWindow = new BrowserWindow({width: 800, height: 600})
mainWindow.loadURL(url.format({
pathname: path.join(__dirname, 'index.html'),
protocol: 'file:',
slashes: true
}))
mainWindow.on('closed', function () {
mainWindow = null
})
}
app.on('ready', createWindow)
app.on('window-all-closed', function () {
if (process.platform !== 'darwin') {
app.quit()
}
})
app.on('activate', function () {
if (mainWindow === null) {
createWindow()
}
})
The middle click does not create a new instance of your application, but rather a new instance of a BrowserWindow. You can disable middle-clicks on a (actually all) elements using the auxclick event.
In your main window's HTML you could put the following JavaScript to disable middle-clicks on link elements if you do not want to redirect these events to your default browser:
// The following function will catch all non-left (middle and right) clicks
function handleNonLeftClick (e) {
// e.button will be 1 for the middle mouse button.
if (e.button === 1) {
// Check if it is a link (a) element; if so, prevent the execution.
if (e.target.tagName.toLowerCase() === "a") {
e.preventDefault();
}
}
}
window.onload = () => {
// Attach the listener to the whole document.
document.addEventListener("auxclick", handleNonLeftClick);
}
But you can also choose to redirect the middle-click events to your standard browser, namely via Electron's shell module:
// Require Electron's "shell" module
const { shell } = require("electron");
function handleNonLeftClick (e) {
// e.button will be 1 for the middle mouse button.
if (e.button === 1) {
// Check if it is a link (a) element; if so, prevent the execution.
if (e.target.tagName.toLowerCase() === "a") {
// Prevent the default action to fire...
e.preventDefault();
// ...and let the OS handle the URL.
shell.openExternal(e.target.href);
}
}
}
// Also attach the listener this time:
window.onload = () => { document.addEventListener("auxclick", handleNonLeftClick); }
You could remove the if (e.button === 1) if you also want to block right-clicks on a elements.

Resources