问题
Is there a way to see that a browser window is minimized while the user is switching to the other window on IPhone? Same about when the browser window becomes inactive by switching to any other application.
I've tried to bind to jQuery onfocus, onblur events ($(window).blur(...);
) but got no callbacks.
Thanks!
回答1:
I think the closest thing to what you're looking for are the pageshow and pagehide events. In tests I did in iOS 5.1, when switching to another application from Mobile Safari after double-pressing the home button, the pagehide
event seemed to be fired immediately before the application actually switched, whereas if I pressed the home button just once to get to the home screen it seems the JavaScript thread is suspended immediately and listeners for the event are only called when Mobile Safari is brought into focus again.
This is how you would listen for the events:
window.addEventListener('pageshow', myPageShowListenerFunc, false);
window.addEventListener('pagehide', myPageHideListenerFunc, false);
回答2:
For later versions of iOS pageshow
and pagehide
don't work reliably anymore. However, you can now use the visibilitychange
event, which is triggered when the user opens another browser tab, or when the browser is minimised (by pressing the home button).
So your code would look like
window.addEventListener('visibilitychange', myVisibilityHandleFunc, false);
or with jQuery
$(document).on('visibilitychange', myVisibilityHandleFunc);
From MDN:
The Page Visibility API lets you know when a webpage is visible or in focus. With tabbed browsing, there is a reasonable chance that any given webpage is in the background and thus not visible to the user. When the user minimizes the webpage or moves to another tab, the API sends a visibilitychange event regarding the visibility of the page.
There is a property called document.webkitHidden
that can be used for iPhones, to know if the change was visible -> hidden, or hidden -> visible.
来源:https://stackoverflow.com/questions/10071397/is-there-a-way-to-see-that-a-browser-window-is-minimized-while-the-user-is-switc