12

i'm binding a function to an event with

window.onbeforeunload = function() {
 somefunction()
}

which is working on unload as planned, but if they cancel the onbeforeunload the function is still attached, is it possible to check if the user cancels onbeforeunload

James Kirkby
  • 1,716
  • 5
  • 24
  • 46
  • 3
    What do you mean by `cancel the onbeforeunload`? – VisioN Nov 18 '13 at 20:25
  • possible duplicate of [window.onbeforeunload handling ok and cancel options](http://stackoverflow.com/questions/5579326/window-onbeforeunload-handling-ok-and-cancel-options) – showdev Nov 18 '13 at 20:26

3 Answers3

31

Actually, I found it was quite easy: I just set

window.onbeforeunload = null;

for each click before it was run, allowing the event handler to be run afterwards.

wizzwizz4
  • 6,140
  • 2
  • 26
  • 62
James Kirkby
  • 1,716
  • 5
  • 24
  • 46
  • I'm trying to find a way to suppress the Leave/Stay prompt conditionally, but haven't figured this out yet. If the form is dirty, then I'd like to prompt the user otherwise skip that. Any suggestions? – PongGod Apr 15 '21 at 19:40
  • return undefined should work to supress the prompt. more info: https://stackoverflow.com/questions/7317273/warn-user-before-leaving-web-page-with-unsaved-changes – Topman May 17 '22 at 06:09
3

or you can just return null

window.onbeforeunload = function() {
  return null;
};

I am using following snippet for that: window.onbeforeunload gist

woss
  • 933
  • 1
  • 11
  • 20
  • This doesn't work for me. I still get the Leave/Stay prompt popping up. – PongGod Apr 15 '21 at 18:27
  • 1
    @PongGod: return undefined should work. more info: https://stackoverflow.com/questions/7317273/warn-user-before-leaving-web-page-with-unsaved-changes – Topman May 17 '22 at 06:00
0

also I just add more suggestion with following answer. https://stackoverflow.com/a/20057278/3710376

It can run a function and ignore any popup confirmation.

window.onbeforeunload = function() {
 somefunction()
 window.onbeforeunload = false;
}
Community
  • 1
  • 1