Icon in electron - electron

I have a problem to change icon in Electron.
The code work fine, but when I add the line <<icon: "img/icon.png">> is produced a blank program (without anything).
This is the code:
function createWindow () {
const win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
devTools: false
},
icon: "img/icon.png"
});
win.setMenu(null);
win.loadFile('index.html');
win.webContents.openDevTools();
}

To change icon of the window pass it in BrowserWindow constructor and use absolute path for simplification
icon (NativeImage | String) (optional) - The window icon. On Windows it is recommended to use ICO icons to get best visual effects, you can also leave it undefined so the executable's icon will be used.
You will need to use some converter to generate .ico and .icns files.
let icon;
switch (process.platform) {
case 'win32': icon = path.resolve(__dirname, 'img', 'icon.ico'); break;
case 'darwin': icon = path.resolve(__dirname, 'img', 'icon.icns'); break;
case 'linux': icon = path.resolve(__dirname, 'img', 'icon.png'); break;
}
const win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
devTools: false
},
icon
});
Also, you can create NativeImage like this: const icon = nativeImage.createFromPath(path.resolve(__dirname, 'img', 'icon.png'));
But, you don't actually need to set icons manually, electron will use executable's icon by default. So just configure electron-packager to use proper icons (add packagerConfig: { icon: img/icon } } in forge.config.js and place icon.png, icon.icns and icon.ico into img dir)

Right, but the problem is that doesn't exist anything of error.
But... I've just done another attempt with the following command: electron-package --overwrite --icon=icon.ico
Now works!!! but the question is: WHY ???

Related

Unable to remove menu in development for Electron

This is my createWindow function that I pass to app.on('ready')
function createWindow () {
const startUrl = process.env.ELECTRON_START_URL || url.format({
pathname: path.join(__dirname, '../index.html'),
protocol: 'file:',
slashes: true,
})
mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
devTools: true,
preload: path.join(__dirname, 'preload.js')
},
})
mainWindow.loadURL(startUrl)
mainWindow.removeMenu() // <----------------- HERE!
mainWindow.on('closed', function () {
mainWindow = null
})
}
Pretty boiler plate the issue is that the mainWindow.removeMenu() does not work and it leaves it in places.
I've also tried setMenu(null) and the menu is still there.
Is the menu only removed in production, or am I doing something wrong?
Edit
I've also tried mainWindow.setMenuBarVisibility(false), and it does not work as well.
Chances are that you are still using an old version of Electron. There has been a bug preventing the removal of the menu bar for a long time. It has been fixed in Electron 7.1.5:
Release Notes for v7.1.5
Fixes
Fixed window menu unable to hide on startup. #21449
So, mainWindow.removeMenu() should work fine once you upgrade Electron to its latest version, or at least a version greater than or equal to 7.1.5.

Electron loadFile is not a function

I'm developing an app using Electron. Using win.loadFile('index.html') used to work, but from yesterday it throws an error saying: win.loadFile is not a function.
Could it be "Knex.js" which caused this error? Because I installed it recently and the problems began to appear after that. Also, I noticed that Electron icon changed from transparent to a light blue (green) circle.
In addition, Using loadURL works but it renders the html file incompletely.
This is my main.js (I removed knex.js code from main.js but didn't help):
const { app, BrowserWindow } = require('electron')
const url = require('url')
const path = require('path')
function createWindow () {
// Create the browser window.
let win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true
}
})
// and load the index.html of the app.
win.loadFile('index.html');
}
app.on('ready', createWindow)
Check your Electron version. The version of Electron you want to run, install it globally. Here's the issue on GitHub:
BrowserWindow .loadFile is not a function

How to restore default window size in an electron app?

Is there a way to restore main window in an electron app to a certain size? To explain what I am trying to accomplish, let me give you an example:
When I open Windows Explorer, it opens with a certain size and at a certain position. Then I maximize that window and close the explorer. Next time when I restart the explorer, it opens in the same state as when I closed it i.e. in maximized state. However when I click on the restore button, explorer restores to the width/height and position before it was maximized.
I would like to accomplish the same in my electron application as well. However that is not happening.
What I am doing is when my application closes, I capture the dimensions (width, height) and position (x, y coordinates) of the application window using (win.getBounds())and save those in a config file using electron-config. This is what my code looks like:
const Config = require('electron-config')
const config = new Config();
mainWindow.on('close', () => {
config.set('winBounds', mainWindow.getBounds())
});
Now when I start the application, I read the settings from the config file (actually electron-config does that for me) and use that to set the initial dimensions/position of the window. I am using code like below:
let opts = {
show: false,
icon: path.join(__dirname, 'app-window-icon.png')
};
Object.assign(opts, config.get('winBounds'));
mainWindow = new BrowserWindow(opts);
This is also working great. However the only option I get now is maximize the window. I'm not able to find any option to restore the window to a size before it was maximized.
For example, let's say the user launches the application with 1024x768 px dimensions. User then maximizes the application window and then closes it. When the user relaunches the application, it opens with the size it was closed and the only option I see is to maximize the window. What I am looking for is an option to restore the window size to 1024x768px.
I looked up the documentation here: https://github.com/electron/electron/blob/master/docs/api/browser-window.md but unfortunately couldn't find anything there.
I used the solution here which involves persisting your windows size and position in electron-settings and it works perfectly.
Include the windowStateKeeper function in your code and then adapt your createMainWindow function as follows:
function createMainWindow() {
const mainWindowStateKeeper = windowStateKeeper('main');
const win = new electron.BrowserWindow({
title: 'main',
x: mainWindowStateKeeper.x,
y: mainWindowStateKeeper.y,
width: mainWindowStateKeeper.width,
height: mainWindowStateKeeper.height
});
mainWindowStateKeeper.track(win);
win.loadURL(`file://${__dirname}/index.html`);
win.on('closed', onClosed);
return win;
}
Here is complete solution:
stateKeeper.ts:
import {screen} from 'electron';
import settings from 'electron-settings';
export const windowStateKeeper = async (windowName) => {
let window, windowState;
const setBounds = async () => {
// Restore from appConfig
if (await settings.has(`windowState.${windowName}`)) {
windowState = await settings.get(`windowState.${windowName}`);
return;
}
const size = screen.getPrimaryDisplay().workAreaSize;
// Default
windowState = {
x: undefined,
y: undefined,
width: size.width / 2,
height: size.height / 2,
};
};
const saveState = async () => {
// bug: lots of save state events are called. they should be debounced
if (!windowState.isMaximized) {
windowState = window.getBounds();
}
windowState.isMaximized = window.isMaximized();
await settings.set(`windowState.${windowName}`, windowState);
};
const track = async (win) => {
window = win;
['resize', 'move', 'close'].forEach((event) => {
win.on(event, saveState);
});
};
await setBounds();
return {
x: windowState.x,
y: windowState.y,
width: windowState.width,
height: windowState.height,
isMaximized: windowState.isMaximized,
track,
};
};
main.ts
import {windowStateKeeper} from './utils/windowStateKeeper';
const mainWindowStateKeeper = await windowStateKeeper('main');
// Create the browser window.
mainWin = new BrowserWindow({
title: 'Desktop',
x: mainWindowStateKeeper.x,
y: mainWindowStateKeeper.y,
width: mainWindowStateKeeper.width,
height: mainWindowStateKeeper.height,
webPreferences: {
nodeIntegration: true,
allowRunningInsecureContent: serve ? true : false,
contextIsolation: false, // false if you want to run e2e test with Spectron
enableRemoteModule: true, // true if you want to run e2e test with Spectron or use remote module in renderer context (ie. Angular)
},
});
// Track window state
mainWindowStateKeeper.track(mainWin);
I implemented this after a lot of testing this is the most accurate and simple solution to remember window properties.
i used electron-store to store values, you can use any storage methods you like.
main.js
let windowConfig = {
width: 1280,
height: 680,
}
function createWindow() {
Object.assign(windowConfig, CONFIG.get("winBounds"))
mainWindow = new BrowserWindow(windowConfig)
if (windowConfig.isMaximized) {
mainWindow.maximize()
}
mainWindow.on("close", () => {
Object.assign(windowConfig, {
isMaximized: mainWindow.isMaximized()
}, mainWindow.getNormalBounds())
CONFIG.set("winBounds", windowConfig) // saves window's properties using electron-store
})
}

Electron Take Up 100% Of Screen (Not Full Screen)

I've got an electron app, below is the main.js file:
var app = require('electron').app;
var BrowserWindow = require('electron').BrowserWindow;
app.on('ready', function() {
mainWindow = new BrowserWindow({
height: 715,
width: 1200,
minWidth: 600,
minHeight: 200,
center: true
});
mainWindow.loadURL('file://' + __dirname + '/index.html');
});
As you can see, the width and height are specified. What I want is for the app to open, but take up all of the available screen (but NOT to be in full screen, such that the dock and tool bar of the OS are hidden).
In simple CSS this is done by using
width:100%;
height:100%;
I want to be able to reproduce this in my electron app, although cannot seem to find any details on how to do it
Note: fullscreen: true is not what I am looking for, as that makes the app open so that the dock and toolbar are hidden
Can anyone help?
use this!
win = new BrowserWindow({show: false});
win.maximize();
win.show();
Call mainWindow.maximize() to maximize the window after you create it.
Use this:
const electron = require('electron')
const { app, BrowserWindow } = electron
let win
app.on('ready', () => {
const {width, height} = electron.screen.getPrimaryDisplay().workAreaSize
win = new BrowserWindow({width, height})
win.loadURL('https://github.com')
})
try this code after your mainWindow declaration
mainWindow.once('ready-to-show', () => {
mainWindow.maximize()
})
It worked for me
The solution is simple, only add titleBarStyle: 'hidden' to declaration of your window.
const mainWindow = new BrowserWindow({
movable: false,
resizable: false,
maximizable: false,
minimizable: false,
titleBarStyle: 'hidden', // watch this line
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
DevTools: false,
}
});
note that I only have tested on Windows OS and it can be change in other OS like Mac.

How to set OverlayIcon on Electron windows app build for release with Squirrel.Windows

I have packed the entire sources into one .exe folder. The icon of the app is set but my problem is that it does not recognise (same icon in my case) for setting overlay.
The code extracted from package.js to make build:
"pack": "build --dir",
"dist": "build --win --ia32"
"build": {
"icon": "icon.ico"
}
And in index.html when i receive an event and need to overlay the icon it goes out the door and throws error. Same icon i use to set for the app.
mainWindow = new BrowserWindow({width: 1200, height: 800, icon: `icon.ico`, title: title})
I don't understand where is that path coming from... I expected to be the path of the icon from the resources of the app. The same one used for setting app icon. Lost on ideas here...Please help.
Relevant part from index.html
<script type="text/javascript">
const remoteElectron = require('electron').remote;
const BrowserWindow = remoteElectron.BrowserWindow;
const electron = require("electron");
var win = remoteElectron.getCurrentWindow();
var eventNewmsg = window.document.createEvent('Event');
eventNewmsg.initEvent('okmsg', false, false);
window.document.addEventListener("okmsg", function(){
win.setOverlayIcon(`icon.ico`, "");
}, false);
window.eventNewMsg = eventNewmsg;
var eventNomsg = window.document.createEvent('Event');
eventNomsg.initEvent('cancelmsg', false, false);
window.document.addEventListener("cancelmsg", function(){
win.setOverlayIcon(null, "")
}, false);
window.eventNoMsg = eventNomsg;
</script>
It's best to be explicit when specifying paths, so if your icon is in the same directory as index.html you should do the following:
const path = require('path');
win.setOverlayIcon(path.join(__dirname, 'icon.ico', ''));
Uhm i set in a different way the icon, and works pretty fine for me.
I'll leave you how i set it. works in all places.
mainWindow = new BrowserWindow({
transparent: false,
frame: false,
fullscreen: false,
width: 800,
height: 400,
resizable: false,
movable: false,
show: false,
icon: __dirname + '/styles/images/app.png'
});

Resources