Ali Ahmadi
Ali Ahmadi

Reputation: 133

Th Electron Window OnBlur Event [unhandled error]

This error occurs seldom in the app when it loads (Not all the time). The index.js is the main file ,selected in package.json, and the script.js is the file connected to main html file of the electron app.

enter image description here index.js

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

let window;

var APP_DIR = '/app/';
var IMG_DIR = '/images/';

function createWindow() {
    window = new BrowserWindow({
        webPreferences: { nodeIntegration: true },
        width:610,
        height:679,
        icon: path.join(__dirname, APP_DIR, IMG_DIR, 'icon.png'),
        frame: false,
        resizable: false,
        fullscreenable: false
    });

    window.loadURL(url.format({
        pathname: path.join(__dirname, APP_DIR, 'index.html'),
        protocol: 'file:',
        slashes: true
    }));
}

app.on('ready', createWindow);

script.js (where the error occurs)

var {BrowserWindow} = require('electron').remote;

BrowserWindow.getFocusedWindow().on('blur', function() {
    windowBlurHandler(); //a function
});

How can I fix it?

Upvotes: 1

Views: 1283

Answers (1)

AlekseyHoffman
AlekseyHoffman

Reputation: 2694

Function BrowserWindow.getFocusedWindow() returns null when all windows are blurred. You are getting the error because listeners cannot be registered on null.

Try something like this instead:

const mainWindow = require('electron').remote.getCurrentWindow()

mainWindow.on('blur', function() {
  windowBlurHandler()
})

Upvotes: 3

Related Questions