2

I have some replaying functionality working by using Javascript and the window.onload function.

However when I go to some other page and then come back to the web application (with the onload function) it's no longer working since the page has not been refreshed (or loaded).

Is there a way I could refresh the functionality in the window.onload function if the user doesn't close off the page but it's in the background and after a while comes back and have it on focus?

Edit - bad question. After testing I realised this behaviour is with chrome only but works fine in IE and firefox. Sorry guys, I really thought it was a bug

D. Rattansingh
  • 1,569
  • 3
  • 19
  • 30
  • 2
    you can disable the page caching, causing the page to reload even after hitting 'back' – avrahamcool Dec 16 '13 at 14:29
  • Related question which might have your solution: http://stackoverflow.com/questions/3479734/javascript-jquery-test-if-window-has-focus check out the fiddle in the answer – Milanzor Dec 16 '13 at 14:36
  • It's not the back button I'm referring to. I've got 5 tabs open (chrome), tab 1 is the application executing the infinite loop functionality. I then switch for tab 3 for a while and when I come back to tab 1 the loop has stopped. – D. Rattansingh Dec 16 '13 at 21:16

2 Answers2

0

I assume with "coming back" you mean "re-opening the window / tab with your website", instead of "pressing the back button after the user really left the page", in which case onLoad should fire as well.

You can use the window.onFocus() event for that. Note that it is called each time the window/tab is focused again, so it might fire more often than you'd like it to. You can prevent that by saving the timestamp of your last refresh and comparing against the last timestamp. I.e. implement a "timeout" for your page, and reload it onFocus only, when the last refresh is older than X seconds.

Kaii
  • 20,122
  • 3
  • 38
  • 60
0

The onload event should be fired when the user hits the back button. Elements not created via JavaScript will retain their values. I suggest keeping a backup of the data used in dynamically created element within an <input type="hidden"> set to display:none then onload using the value of the textbox to rebuild the dynamic elements to the way they were.

If you don't care about rebuilding the page and want to actually reload it, then you could do:

<input type="hidden" id="refreshed" value="no">

 <script type="text/javascript">
    onload=function(){
    var e=document.getElementById("refreshed");
    if(e.value=="no")e.value="yes";
    else{e.value="no";location.reload();}
    }
   </script>
Kaii
  • 20,122
  • 3
  • 38
  • 60
Anand Jha
  • 10,404
  • 6
  • 25
  • 28
  • It's switching tabs I'm referring to so the window isn't loading again. Tried the onfocus but it's executing continously causing the timer to be started many times – D. Rattansingh Dec 16 '13 at 21:19