Reputation: 41
I have a simple Electron app. The main process would open up a browser window (I call it mainWindow
) and I would like to prevent users from closing it (for kiosk purposes; FYI, I already have kiosk: true
. I'm just trying to add another layer of protection).
I have set up a beforeunload
event listener in my renderer process like shown below:
window.onbeforeunload = (e) => {
console.log('I do not want to be closed')
e.returnValue = false
}
This works well. It prevents closing of the window in every way (at least in macOS) and I could quit the process with mainWindow.destroy()
in the main process. However, by doing this, I am not able to redirect my window to any other HTML files, no matter with location.href
or mainWindow.loadFile()
because it would fire the beforeunload
event and prevent it from redirecting.
One solution I could think of is to use a fullscreen iframe
in mainWindow
and do the redirections there, but the communication between sandboxed iframe
and the window that uses ipcRenderer
would be too complex.
Apart from that, is there a work around to distinguish whether a beforeunload
event was fired for it being closed or just being redirected?
Upvotes: 0
Views: 236
Reputation: 3432
Instead of using the DOM onbeforeunload
handler, you could listen for the BrowserWindow
's very own close
event in the Main Process, which is emitted before onbeforeunload
but only when the window is actually going to close.
As per the documentation, you would have to call e.preventDefault ()
to prevent closing, but you wouldn't have to worry about page redirects.
const { BrowserWindow } = require ("electron");
let window;
// However you're initialising your BrowserWindow...
window.on ("close", event => {
event.preventDefault ();
});
The documentation for #destroy ()
states that it will not emit the "close"
event, thus everything should work as before, except you're listening for the event on the Main Process and gain window reloading.
Upvotes: 1