Electron.js Prevent refresh for created window
Asked Answered
P

2

6

I'm trying to disable Cmd+R or F5 for refreshing my electron app like so:

  globalShortcut.register('CommandOrControl+R', () => false);
  globalShortcut.register('F5', () => false);

But, unfortunately, it cause preventing refresh entirely for all frames, even for other browsers.

How can I register such shortcuts only for my created window?

ALTERNATIVE: I guess, we could use Mousetrap as an option for such operation, but I wonder - is there any kinda built in method for such operation?

Periodate answered 5/7, 2018 at 9:17 Comment(3)
have u seen this? electronjs.org/docs/tutorial/… (mousetrap is suggested there too)Kosak
But mouse trap doesn't work inside a input fields isn't ?Codie
There seems to be a built-in functionality of CMD+R in electron, as it's impossible to catch this event in the browser window and preventing it from propagation. The event is caught, but the page reloads even with stopPropagation(), preventDefault() or return false... Any ideas anyone?Es
P
3

This is the most appropriate way to prevent Window refresh. The other approaches don't prevent window.reload() calls.

The ev object hold information about what triggered the unload event, it could be used to tailor the outcome of the event in any way you wish.

window.addEventListener('beforeunload', (ev) => {
      // Setting any value other than undefined here will prevent the window
      // from closing or reloading
      ev.returnValue = true;
    });
Puttergill answered 7/5, 2020 at 18:6 Comment(3)
this looks like it is preventing also the app from closing though :DFloccus
Yes it does, but from that context you will have to treat all edge cases like I said on the 2nd paragraph. the ev holds info about the origin of the event. based on that you can display a message asking the user if they really want to quit for example.Koopman
@JoãoEduardoSoareseSilva Give me a simple example how can I distinguish between beforeunload event produced by Ctrl+R and the one emitted when I try to close the app window. All the properties in both events look the same to me.Cleanlimbed
T
1

I use this code and work only with keyboard

win.webContents.on('before-input-event', (event, input) => {
    if (input.control && input.key.toLowerCase() === 'r') {
        event.preventDefault()
    }
})
Tillandsia answered 20/8, 2023 at 19:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.