Click here to Skip to main content
15,888,461 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
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:-

JavaScript
$(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?";
            }


What I have tried:

I have tried above function.
Even tried window.onload and window.onunload events. But none are working as per my scenario.
Posted
Updated 29-Mar-18 0:50am

1 solution

You can't find out when the user has closed their browser. If you don't want the data to persist then use session storage rather than local storage

Window sessionStorage Property[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900