prevent OnBeforeUnload() event from happening in refresh/F5

Refael picture Refael · Oct 23, 2013 · Viewed 7.4k times · Source

I'm using onbeforeunload event to perform operations during the closing page.
I do not want the event to happen in the case of Refresh / F5.

Is there a way or other event to do this?

Answer

zur4ik picture zur4ik · Oct 23, 2013

Unfortunately onbeforeunload event listens the page state in the browser. Going to another page as well as refreshing will change the page state, meaning onbeforeunload will be triggered anyway.

So I think it is not possible to catch only refresh.

But, if you'll listen and prevent Keypress via JavaScript, then it can be achieved.

Refresh can be done via F5 and CtrlR keys, so your goal will be to prevent these actions.

using jQuery .keydown() you can detect these keycodes:

For CtrlR

$(document).keydown(function (e) {
    if (e.keyCode == 65 && e.ctrlKey) {
        e.preventDefault();
    }
});

For F5

$(document).keydown(function (e) {
    if (e.which || e.keyCode) == 116) {
        e.preventDefault();
    }
});