Differentiate between browser reload/refresh/F5 and close event

Posted by Vishalneeraj-24503 under JavaScript on 3/29/2018 | Points: 10 | Views : 1143 | Status : [Member] [MVP] | Replies : 0
Hi All,

I came across a situation where user wants to show message while refreshing a browser or closing a browser.
That i have done using onbeforeunload event which gets called when browser is refreshed or explicitly closed.

In my application, i am using local storage to persist state of the page i.e. get same data with same page while refreshing. So that i can get data from local storage.

But when i explicitly close the browser then in that case i want to clear local storage keys using localStorage.clear() method.

But i am unable to track close as well as refresh/F5 events because onbeforeunload event gets called on both action.

I tried googling that lets us onload/onunload events but these are also not working.

When i refresh a browser/close a browser then it should ask for confirmation message
1). When click "stay on page" then do not do anything.
2). When click "leave this page" then i want to check whether browser refresh happens or close button called and accordingly i want to clear local storage.
Meaning that if refreshed then do not clear local storage. However closed then clear local storage keys.

I have also used session storage but my requirement is to use local storage.

So how to acheive above scenarios:-

My code is below:-

$(window).on('mouseover', (function ()
{
window.onbeforeunload = null;
}));

$(window).on('mouseout', (function ()
{
window.onbeforeunload = ConfirmLeaveMessage;
}));

function ConfirmLeaveMessage()
{
//return undefined;
return "Are you sure you want to leave this page without saving?";
}


I have tried above function.
Even tried window.onload and window.onunload events. But none are working as per my scenario.




Responses

(No response found.)

Login to post response