How to make a splash screen on Electron? - electron

I'm new to Electron and I joined an existing project. I'm trying to add an image before the main screen of the app that will last 5 seconds. At first, I tried it with useState and setTimeone but I've realized I'm in the wrong place of the code.
After reading all kinds of solutions, and running the app - I now need your help.
This is some of the code in my main.ts file:
mainWindow = new BrowserWindow({
show: false,
width: 521,
height: 712,
icon: getAssetPath('icon.png'),
webPreferences: {
nodeIntegration: true,
contextIsolation: true,
preload: app.isPackaged
? path.join(__dirname, 'preload.+212 662-122618 js')
: path.join(__dirname, '../../.erb/dll/preload.js'),
},
});
mainWindow.loadURL(resolveHtmlPath('index.html'));
mainWindow.on('ready-to-show', () => {
if (!mainWindow) {
throw new Error('"mainWindow" is not defined');
}
if (process.env.START_MINIMIZED) {
mainWindow.minimize();
} else {
mainWindow.show();
}
});
mainWindow.on('closed', () => {
mainWindow = null;
});
const menuBuilder = new MenuBuilder(mainWindow);
menuBuilder.buildMenu();
// Open urls in the user's browser
mainWindow.webContents.setWindowOpenHandler((edata) => {
shell.openExternal(edata.url);
return { action: 'deny' };
});
// Remove this if your app does not use auto updates
// eslint-disable-next-line
new AppUpdater();
};
/**
* Add event listeners...
*/
app.on('window-all-closed', () => {
// Respect the OSX convention of having the application in memory even
// after all windows have been closed
if (process.platform !== 'darwin') {
app.quit();
}
});
app
.whenReady()
.then(() => {
createWindow();
app.on('activate', () => {
// 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 (mainWindow === null) createWindow();
});
})
.catch(console.log);

Related

Electron build failed to load index.html

I'm trying to build my electron application with electron-builder, I have successfully built front-end which was react and did also pass homepage: "./" in my package.json. I have also used hashbrowser as it was mentioned here
but still when I build my app, I get this message in console with white screen:
Not allowed to load local resource. I have passed webSecurity: false in webPreferences electron, It made error go away but didn't fix the problem and still getting white page.
this is my electron index.ts:
let mainWindow: BrowserWindow;
const createWidnow = () => {
mainWindowFunctions();
mainWindow = new BrowserWindow({
minHeight: 600,
minWidth: 800,
x: appXAndY.x,
y: appXAndY.y,
width: appWidthAndHeight.width,
height: appWidthAndHeight.height,
webPreferences: {
nodeIntegration: true,
contextIsolation: false,
preload: path.join(__dirname, "preload.js"),web
},
autoHideMenuBar: true,
});
mainWindow.loadURL(
isDev ? "http://localhost:3000/" : `file://${__dirname}/../build/index.html`
);
if (isDev) {
mainWindow.webContents.openDevTools();
}
}
app.whenReady().then(async () => {
createWidnow();
app.on("activate", () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWidnow();
}
});
});
app.on("window-all-closed", () => {
if (process.platform !== "darwin") {
db.close();
app.quit();
}
});
const mainWindowFunctions = () => {
const files = glob.sync(
path.join(__dirname, "./controllers/**/*.js").split(path.sep).join("/")
);
files.forEach((file) => {
require(file);
});
};
I tried webSecurity false but didn't help
The problem is with Electron Packager. Just use Electron Builder. Then you can get the installer using wix3.

How to make about popup in electron

I want to know how can I add about button in my electron app that opens popup with software details? something like this:
Code
This is how currently my index.js looks like:
const { app, BrowserWindow, Menu } = require('electron');
const isDevMode = require('electron-is-dev');
const { CapacitorSplashScreen, configCapacitor } = require('#capacitor/electron');
const path = require('path');
// Place holders for our windows so they don't get garbage collected.
let mainWindow = null;
// Placeholder for SplashScreen ref
let splashScreen = null;
//Change this if you do not wish to have a splash screen
let useSplashScreen = true;
// Create simple menu for easy devtools access, and for demo
const menuTemplateDev = [
{
label: 'Options',
submenu: [
{
label: 'Open Dev Tools',
accelerator: "CmdOrCtrl+D",
click() {
mainWindow.openDevTools();
},
},
],
},
{
label: 'Help',
submenu: [
{
label: 'Support',
accelerator: "CmdOrCtrl+H",
click: async () => {
const { shell } = require('electron');
await shell.openExternal('https://example.com/contact-us');
}
},
{ type: 'separator' },
{
label: 'Quit!',
accelerator: "CmdOrCtrl+Q",
click() {
app.quit();
}
}
]
}
];
const menuTemplateProd = [
{
label: 'Help',
submenu: [
{
label: 'Support',
accelerator: "CmdOrCtrl+H",
click: async () => {
const { shell } = require('electron')
await shell.openExternal('https://example.com/contact-us')
}
},
{ type: 'separator' },
{
label: 'Quit!',
accelerator: "CmdOrCtrl+Q",
click() {
app.quit();
}
}
]
}
];
async function createWindow () {
// Define our main window size
mainWindow = new BrowserWindow({
height: 920,
width: 1600,
show: false,
// icon: __dirname + '/Icon/Icon.icns',
webPreferences: {
nodeIntegration: true,
preload: path.join(__dirname, 'node_modules', '#capacitor', 'electron', 'dist', 'electron-bridge.js')
}
});
mainWindow.setIcon(path.join(__dirname, '/splash_assets/logo.png'));
configCapacitor(mainWindow);
if (isDevMode) {
// Set our above template to the Menu Object if we are in development mode, dont want users having the devtools.
Menu.setApplicationMenu(Menu.buildFromTemplate(menuTemplateDev));
// If we are developers we might as well open the devtools by default.
mainWindow.webContents.openDevTools();
} else {
Menu.setApplicationMenu(Menu.buildFromTemplate(menuTemplateProd));
}
if(useSplashScreen) {
splashScreen = new CapacitorSplashScreen(mainWindow);
splashScreen.init();
} else {
mainWindow.loadURL(`file://${__dirname}/app/index.html`);
mainWindow.webContents.on('dom-ready', () => {
mainWindow.show();
});
}
}
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some Electron APIs can only be used after this event occurs.
app.on('ready', createWindow);
// Quit when all windows are closed.
app.on('window-all-closed', function () {
// On OS X it is common for applications and their menu bar
// to stay active until the user quits explicitly with Cmd + Q
if (process.platform !== 'darwin') {
app.quit();
}
});
app.on('activate', function () {
// 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 (mainWindow === null) {
createWindow();
}
});
// Define any IPC or other custom functionality below here
Any suggestions?
SOLVED
I've added new window function and new index file. And changed my index.js to the following code:
const { app, BrowserWindow, Menu } = require('electron');
const isDevMode = require('electron-is-dev');
const { CapacitorSplashScreen, configCapacitor } = require('#capacitor/electron');
const path = require('path');
// Place holders for our windows so they don't get garbage collected.
let mainWindow = null;
let childWindow = null; // <---- ADDED
// Placeholder for SplashScreen ref
let splashScreen = null;
//Change this if you do not wish to have a splash screen
let useSplashScreen = true;
// Create simple menu for easy devtools access, and for demo
const menuTemplateDev = [
{
label: 'Options',
submenu: [
{
label: 'Open Dev Tools',
accelerator: "CmdOrCtrl+D",
click() {
mainWindow.openDevTools();
},
},
],
},
{
label: 'Help',
submenu: [
{ // <---- ADDED
label: 'About', // <---- ADDED
accelerator: "F1", // <---- ADDED
click: async () => { // <---- ADDED
createAboutWindow(); // <---- ADDED
} // <---- ADDED
}, // <---- ADDED
{
label: 'Support',
accelerator: "CmdOrCtrl+H",
click: async () => {
const { shell } = require('electron');
await shell.openExternal('https://example.com/contact-us');
}
},
{ type: 'separator' },
{
label: 'Quit!',
accelerator: "CmdOrCtrl+Q",
click() {
app.quit();
}
}
]
}
];
const menuTemplateProd = [
{
label: 'Help',
submenu: [
{ // <---- ADDED
label: 'About', // <---- ADDED
accelerator: "F1", // <---- ADDED
click: async () => { // <---- ADDED
createAboutWindow(); // <---- ADDED
} // <---- ADDED
}, // <---- ADDED
{
label: 'Support',
accelerator: "CmdOrCtrl+H",
click: async () => {
const { shell } = require('electron')
await shell.openExternal('https://example.com/contact-us')
}
},
{ type: 'separator' },
{
label: 'Quit!',
accelerator: "CmdOrCtrl+Q",
click() {
app.quit();
}
}
]
}
];
async function createWindow () {
// Define our main window size
mainWindow = new BrowserWindow({
height: 920,
width: 1600,
show: false,
// icon: __dirname + '/Icon/Icon.icns',
webPreferences: {
nodeIntegration: true,
preload: path.join(__dirname, 'node_modules', '#capacitor', 'electron', 'dist', 'electron-bridge.js')
}
});
mainWindow.setIcon(path.join(__dirname, '/splash_assets/logo.png'));
configCapacitor(mainWindow);
if (isDevMode) {
// Set our above template to the Menu Object if we are in development mode, dont want users having the devtools.
Menu.setApplicationMenu(Menu.buildFromTemplate(menuTemplateDev));
// If we are developers we might as well open the devtools by default.
mainWindow.webContents.openDevTools();
} else {
Menu.setApplicationMenu(Menu.buildFromTemplate(menuTemplateProd));
}
if(useSplashScreen) {
splashScreen = new CapacitorSplashScreen(mainWindow);
splashScreen.init();
} else {
mainWindow.loadURL(`file://${__dirname}/app/index.html`);
mainWindow.webContents.on('dom-ready', () => {
mainWindow.show();
});
}
}
async function createAboutWindow () { // <---- ADDED
// Define our main window size
childWindow = new BrowserWindow({ // <---- ADDED
height: 400, // <---- ADDED
width: 600, // <---- ADDED
show: false, // <---- ADDED
minimizable: false, // <---- ADDED
maximizable: false, // <---- ADDED
parent: mainWindow, // <---- ADDED
// icon: __dirname + '/Icon/Icon.icns', // <---- ADDED
webPreferences: { // <---- ADDED
nodeIntegration: true, // <---- ADDED
preload: path.join(__dirname, 'node_modules', '#capacitor', 'electron', 'dist', 'electron-bridge.js') // <---- ADDED
} // <---- ADDED
}); // <---- ADDED
childWindow.setIcon(path.join(__dirname, '/splash_assets/logo.png')); // <---- ADDED
configCapacitor(childWindow); // <---- ADDED
childWindow.removeMenu(); // <---- ADDED
childWindow.loadURL(`file://${__dirname}/index_child.html`); // <---- ADDED
childWindow.webContents.on('dom-ready', () => { // <---- ADDED
childWindow.show(); // <---- ADDED
}); // <---- ADDED
} // <---- ADDED
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some Electron APIs can only be used after this event occurs.
app.on('ready', createWindow);
// Quit when all windows are closed.
app.on('window-all-closed', function () {
// On OS X it is common for applications and their menu bar
// to stay active until the user quits explicitly with Cmd + Q
if (process.platform !== 'darwin') {
app.quit();
}
});
app.on('activate', function () {
// 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 (mainWindow === null) {
createWindow();
}
if (childWindow === null) { // <---- ADDED
createAboutWindow(); // <---- ADDED
} // <---- ADDED
});
// Define any IPC or other custom functionality below here
Final result
Hope it can help those in need :) .

Changing the ipcMain File in Electron

Hello i'm new to Electron and i want to split my code into separate files and i really would like to move my ipcMain.on Fucntions to another file from main.ts . How can i do that because i don't know if i move it to another file, how should i call it?
and is there any way to use mainWindow.webContents.send() inside another file?
main.ts
import { app, BrowserWindow, ipcMain } from 'electron';
import isDev from 'electron-is-dev';
import path from 'path';
import db from './database/database';
let mainWindow: BrowserWindow;
const createWindow = () => {
mainWindow = new BrowserWindow({
minWidth: 980,
minHeight: 600,
webPreferences: {
nodeIntegration: true,
},
frame: false,
});
mainWindow.loadURL(
isDev
? 'http://localhost:3000'
: `file://${path.join(__dirname, "../build/index.html")}`
);
mainWindow.webContents.openDevTools();
};
app.whenReady().then(createWindow);
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow();
}
});
ipcMain.on('mainWindow:close', () => {
db.close();
app.quit();
});
ipcMain.on('mainWindow:min', () => {
mainWindow.minimize();
});
ipcMain.on('mainWindow:max', () => {
if (mainWindow.isMaximized()) {
mainWindow.unmaximize();
}
else {
mainWindow.maximize();
}
});

How to disable fullscreen on electron window (linux)

These are the only four attributes mentioned in docs.
(1) minimizable
(2) maximizable
(3) fullscreen
(4) fullscreenable
While former two specify that these aren't implemented on Linux, the latter two are for mac only.
So, how do I prevent user from making the window occupy full screen on Linux? And what's the point of having max height and max width properties then (I can't drag and resize beyond those but I can still maximize the window)?
Code:
const { app, BrowserWindow,Menu } = require('electron');
const path = require('path');
require('electron-reload')(__dirname, {
electron: path.join(__dirname,'..', 'node_modules', '.bin', 'electron')
});
// Handle creating/removing shortcuts on Windows when installing/uninstalling.
if (require('electron-squirrel-startup')) { // eslint-disable-line global-require
app.quit();
}
let mainWindow;
const createWindow = () => {
mainWindow = new BrowserWindow({
width: 550,
height: 500,
skipTaskbar: true,
maxWidth:1000,
maxHeight:800,
show:false,
fullscreenable:false,
fullscreen: false,
maximizable: false
});
mainWindow.loadURL({url});
mainWindow.once('ready-to-show', () => {
mainWindow.show()
})
mainWindow.on('closed', () => {
mainWindow = null;
});
};
app.on('ready', createWindow);
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});
app.on('activate', () => {
if (mainWindow === null) {
createWindow();
}
});
Indeed, as said in the docs, maximizable has not been implemented in Linux.
I have not found a "proper" solution, but a work-around.
You should be able to listen to the maximize event, and then call the unmaximize method (I don't see any warning about this event or method about Linux so they should be available). So essentially you would "cancel" the maximizing.
mainWindow.on('maximize', () => {
mainWindow.unmaximize()
});
set resizable key to false:
mainWindow = new BrowserWindow({
resizable: false
});
This should disable the fullscreen button on the m

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