Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add an icon to electron application

I've got my electron build files for a win .exe and installer but the icons aren't mine. In my main.js file, I have code to attach the icon but I can only make it work inside of the createWindow function. Outside the function, I get an error message. The .exe will run and I get my icon, though it's I get an error in doing so; the installer won't work at all. I've tried going through several tutorials but none of them solve this problem.

main.js

const {app, BrowserWindow, Tray} = require('electron')
const path = require('path')
const url = require('url')

let win

function createWindow () {
  const appIcon = new Tray('icon/app.png')
  win = new BrowserWindow({ width: 1920, height: 1080, icon: 'icon/app.ico' })
  console.log(appIcon, win)
  win.loadURL(url.format({
    pathname: path.join(__dirname, 'app/app.html'),
    protocol: 'file:',
    slashes: true
  }))
  win.on('closed', () => {
    win = null
  })
}

app.on('ready', createWindow)
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})
app.on('activate', () => {
  if (win === null) {
    createWindow()
  }
})

package.json

{
  "name": "myapp",
  "version": "1.0.0",
  "description": "MyApp",
  "private": true,
  "main": "main.js",
  "build": {
    "appID": "myapp",
    "productName": "MyApp",
    "icon": "icon/app.ico"
  },
  "scripts": {
    "start": "electron ." ,
    "package": "",
  },
  "author": "Me",
  "license": "ISC",
  "devDependencies": {
    "electron": "^1.6.1"
  }
}

I'm not sure what to do from here.

like image 743
Tim Avatar asked Mar 08 '17 23:03

Tim


2 Answers

Simple solution

const nativeImage = require('electron').nativeImage;
    var image = nativeImage.createFromPath(__dirname + '/public/img/logo.png'); 
 // where public folder on the root dir

    image.setTemplateImage(true);


 // Create the browser window.
    win = new BrowserWindow({
        width: 1179,
        height: 754,
        backgroundColor: '#ffffff',
        transparent: false,
        icon: image
    })
like image 138
Shashwat Gupta Avatar answered Oct 01 '22 20:10

Shashwat Gupta


inside the main.js

mainWindow = new BrowserWindow({width: 800, height: 600,icon: __dirname + '/icon.ico'});

and on the installer, if you are using electron-builder

  "devDependencies": {
    "electron": "^1.4.15",
    "electron-builder": "^12.3.1"
  },

make a folder on the root and named build inside that folder add your icon.ico

sometimes you need to restart the electron or build the app 2 times

like image 26
George C. Avatar answered Oct 01 '22 18:10

George C.