Ankur Aggarwal
Ankur Aggarwal

Reputation: 3101

Stop Caching Window Object on back reload

Let assume page url /xyz. I have window object declared at the top of my JS (because I need that throughout) like

window.myObject={
    someWork:true
}

and I am changing the property value like

if(window.myObject.someWork){
   //Do Work
   window.myObject.someWork=false
}

When I click back button from some other page (abc->xyz) my window.myObject.someWork remains false instead of getting re-initialised again at the top (because I think refresh will run the script again). Can you please suggest what is happening around and how to fix this.

Went through this Does back/forward in the browser change javascript variables?. Any fix for this? I am using Chrome and would like to make it work on all browsers

Fixed: Xufox solution is good and worked.It also cache DOM elements on back button. So make sure its not screwing up the code :)

Thanks in advance

Upvotes: 1

Views: 1596

Answers (1)

Sebastian Simon
Sebastian Simon

Reputation: 19485

When you hit the browser’s back button some browsers just get a cached state of the page. This saves some resources as the state of the document usually doesn’t need to change much when going back and forth in the browser history.

There’s a simple fix for that: add an event listener with a dummy function that fires when the page unloads (beforeunload or unload):

// either …
window.addEventListener('beforeunload',function(){});

// … or
window.addEventListener('unload',function(){});

Any appearance of an unload listener seems to clear all the stored variables and states, etc.


Complete code

window.myObject={
  someWork:true
};

if(window.myObject.someWork){
  //Do Work
  window.myObject.someWork=false;
}

window.addEventListener('unload',function(){});

Also read this

Upvotes: 2

Related Questions