Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

prevent OnBeforeUnload() event from happening in refresh/F5

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?

like image 540
Refael Avatar asked Oct 23 '13 08:10

Refael


People also ask

What triggers Onbeforeunload?

The beforeunload event is fired when the window, the document and its resources are about to be unloaded. The document is still visible and the event is still cancelable at this point. This event enables a web page to trigger a confirmation dialog asking the user if they really want to leave the page.

How do you cancel Windows Onbeforeunload?

Cancelable: The beforeunload event can be canceled by user interaction: // by https://developer.mozilla.org/en-US/docs/Web/Events/beforeunload#Example window. addEventListener("beforeunload", function(event) { event. preventDefault(); // Cancel the event as stated by the standard.

What is Onbeforeunload?

The onbeforeunload event occurs when the document is about to be unloaded. This event allows you to display a message in a confirmation dialog box to inform the user whether he/she wants to stay or leave the current page. The default message that appears in the confirmation box, is different in different browsers.


2 Answers

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();
    }
});
like image 196
zur4ik Avatar answered Oct 17 '22 17:10

zur4ik


I would use the keydown listener to check for F5 and set a flag var.

http://api.jquery.com/keydown/

Detecting refresh with browser button is not that easy/possible.

like image 39
Cracker0dks Avatar answered Oct 17 '22 17:10

Cracker0dks