Search code examples
javascriptjqueryhtmlbrowserreload

Detect difference between refresh and reload


I have filled in a form containing my full name and address. When I hit ⌘R, the page refreshes, but the form is still containing the data I filled in.

When I reload the webpage via the reload button on the top left of Google Chrome, the form will be empty.

How can I detect this difference with JavaScript (or jQuery)?


I have tried this:

$(window).on('load', function(){

     localStorage.setItem('gForm_isDone', '{"0":false,"1":false,"2":false,"3":false,"4":false,"5":false,"6":false,"7":false,"8":false,"9":false,"10":false,"11":false}');
     console.log('localStorage emptied');

     console.log(localStorage.getItem('gForm_isDone'));

});

In my scenario, I want to empty the localStorage, but only when the page reloads, not when it refreshes.


Solution

  • use window.onbeforeunload function to check if refresh/reload is pressed and handled the event localStorage.clear()

    window.onbeforeunload = function(){
     var message = 'Are you sure you want to reload?';
      if (typeof evt == 'undefined') {
        evt = window.event;
      }
      if (evt) {
        evt.returnValue = message;
      }
      return message;
    }