Javascript onLoad Executed When Back Button is Pressed
Here is a solution for Javascript onload function not working if back button is pressed.
Example: if you html page onload function and it alerts some message. Then you navigate to some other page by click some link your page.
From the new page if you press back button, the alert function in onload event will not execute. It executes only in IE, but not in FF.
I use 'onFocus' event as a solution.
Create two files as mentioned below. Open the page1.html in firefox browser.
Then click the link 'Step 1', you will be landed in page2.html.
Now press back button, onFocus event will fire instead of onLoad.
onFocus should point to the onLoad function with wrapper function to avoid some infinite calls and detect browsers.
Name: page1.html
<HTML>
<HEAD>
<TITLE> New Document </TITLE>
<script>
var flag;
flag = 1;
function step1(){
if (navigator.userAgent.indexOf('MSIE') !=-1)
{
return true;
}
if(flag == 0){
flag = 1;
FireAlert(1);
}
}
function FireAlert(){
alert(1);
}
</script>
</HEAD>
<BODY onLoad='FireAlert();flag=0;' onFocus='step1()'>
Hi
<a href='page2.html' onClick='flag=0;'>Step 1</a>
</BODY>
</HTML>
Name: page2.html
<HTML>
<HEAD>
<TITLE> New Document </TITLE>
</HEAD>
<BODY>
Hi,<br>
Click 'Back' button to go back
</BODY>
</HTML>
Look, I have reset the flag to 0 in onClick evening the anchor tag. If you have too many links your page, use DOM alternate 'document.click = 'flag=0'; or assign some function where you can reset the flag.
This is a simple solution, you can change or enhance according to your requirement. Best for Ajax based web applications.
|
This was driving me nuts, thanks for the tip. I have pages where jquery 'ready' is used to fade in images, etc; problem was it was not being called when the back button was hit (in firefox and chrome). This seems to have fixed it, nice work.