Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find if electron app is in foreground?

Tags:

electron

I have a requirement where I want to perform an action inside the electron app only when it is in foreground.

It is an electron-react application. On mounting of a component, I want to schedule a periodic task which only runs when the app is in focus or is being used by the user. And pause the task when the app goes in background.

How can we detect the Electron app being in foreground?

like image 529
amal Avatar asked Dec 13 '22 12:12

amal


2 Answers

You can use the isFocused method from BrowserWindow. To get your own BrowserWindow, you can do this :

remote.BrowserWindow.getAllWindows();

This will return all your app's windows. So to get the first / primary window, you could deconstruct the array like this :

const [yourBrowserWindow] = remote.BrowserWindow.getAllWindows();
console.log(yourBrowserWindow.isFocused());
like image 188
Seblor Avatar answered Dec 28 '22 09:12

Seblor


You can use the focus / blur events on your BrowserWindow to be notified when the app is focused / unfocused.

mainWindow = new BrowserWindow({})

mainWindow.on('focus', () => {
    console.log('window got focus')
})

mainWindow.on('blur', () => {
    console.log('window blur')
})

You may want to update the component's state within these event handlers or use any other method to keep track of the current focus status.

This assumes that you have a single application window. If you have multiple, you'll need to extend the check to cover all of your windows.

like image 37
snwflk Avatar answered Dec 28 '22 10:12

snwflk