I have the following handler:
$(window).bind('pageshow', function() { alert("back to page"); });
When I navigate away from the page (by pressing on a link) and return back to the page (by pressing the "back" button), the alert() is not called (IPad 2, iOS 5.1).
What am I doing wrong please? Any other event I need to bind to?
PS: interesting that pagehide is received properly when navigating away from the page.
You can check the persisted
property of the pageshow
event. It is set to false on initial page load. When page is loaded from cache it is set to true.
window.onpageshow = function(event) {
if (event.persisted) {
alert("back to page");
}
};
For some reason jQuery does not have this property in the event. You can find it from original event though.
$(window).bind("pageshow", function(event) {
if (event.originalEvent.persisted) {
alert("back to page");
}
};
This is likely a caching issue. When you go back to the page via the "back" button, the page is being pulled from the cache (behavior is dependent on the browser). Because of this, your JS will not fire since the page is already rendered in the cache and re-running your js could be detrimental to layout and such.
You should be able to overcome this by tweaking your caching headers in your response or using a handful of browser tricks.
Here are some links on the issue:
- Is there a cross-browser onload event when clicking the back button?
- After travelling back in Firefox history, JavaScript won't run
EDIT
These are all pulled from the above links:
history.navigationMode = 'compatible';
<body onunload=""><!-- This does the trick -->
- "Firefox 1.5+ and some next version of Safari (which contains the fix for bug 28758) supports special events called
pageshow
and pagehide
."
- Using jQuery's
$(document).ready(handler)
window.onunload = function(){};
What you're doing there is binding the return value of alert("back to page")
as a callback. That won't work. You need to bind a function instead:
$(window).bind('pageshow', function() { alert("back to page"); });