iOS Safari Mobile doesn't trigger pageshow fir

2019-02-18 23:39发布

问题:

The iOS Safari doesnt't seem to trigger pageshow event in the following situation.

Lets say I have 3 pages

  • Page A : (has some code code on pageshow event)
  • Page B
  • Page C

User navigates from A -> B. Presses the back button. (pageshow triggers fine)
User then navigates to another page could be Page B or Page C. Then presses the back button again. (pageshow doesn't trigger)

On the contrary if the user minimizes and maximizes the window again or switches to another window and back (by pressing the middle button on iPhone) the pageshow event is triggered again.

Everything seems to work fine on Android

window.onpageshow = function(e) {
  alert('hello');
}

Did anyone else face it? I spent hours on this thing and couldn't think of a workaround.

Any help would be greatly appreciated.

回答1:

Hack : This is what worked for me

var myCustomEvent = (navigator.userAgent.match('iPhone') != null) ? 'popstate' : 'pageshow';

$(window).on(myCustomEvent, function(e) {
 ...
}

For some reason popstate triggers everytime when page state changes in iOS but not in Android.



回答2:

Try using:

window.onpageshow = function(event) {
if (!event.persisted) {
    alert("hello");
}
};

Persisted is false on initial page load, so you can check against it, and if it false, it is your first page load.



回答3:

The popstate event doesn't seem to work any more, at least for me. I worked out some third-party script on my page was breaking this, but wasn't able to work out which one. I came up with this hack:

addEventListener('pageshow', () => {
  history.replaceState({}, document.title, window.location.pathname);
  // called on initial load and first back
});

addEventListener('popstate', () => {
  // called on all back events
});