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.
I add the same problem where iOS does not always post the "pageshow" event when going back.
If not, safari resumes executing JS on the page so I though a timer would continue to fire.
So I came with this solution:
var timer;
function onPageBack() { alert("back to page"); }
window.addEventListener('pageshow', function() {
if (event.persisted)
onPageBack();
// avoid calling onPageBack twice if 'pageshow' event has been fired...
if (timer)
clearInterval(timer);
});
// when page is hidden, start timer that will fire when going back to the page...
window.addEventListener('pagehide', function() {
timer = setInterval(function() {
clearInterval(timer);
onPageBack();
}, 100);
});
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:
EDIT
These are all pulled from the above links:
history.navigationMode = 'compatible';
<body onunload=""><!-- This does the trick -->
pageshow
and pagehide
."$(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"); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With