简体   繁体   中英

can javascript detect if android browser is in foreground or background?

I have this HTML.

<html><body>
<a href="http://mydomain.com/video.mp4">PLAY ME!!!!!</a>
</body></html>
So if somebody clicks on the link then native media player loads and browser goes into background and when video ends it comes to foreground with the same page. Is there a way to detect this ie browser going background and then coming foreground in the javascript?

So as the article that @ndtreviv linked says that "Switching to another document or application." is not implemented in Android yet. However, you can, if you want to, make an app that uses a WebView to display your content. This way, you can access all the native Android stuff from JavaScript.

There is a proposal to allow mobile webapps to detect whether they are in the foreground or not, you can use the "visibilitychange" event, see here: http://www.w3.org/TR/2013/REC-page-visibility-20131029/#sec-visibilitychange-event

Note that this event is fired on the document, not on the window. Eg:

window.document.addEventListener("visibilitychange", function(e) {
  window.console.log('VISIBILITY CHANGE', window.document.visibilityState);
});

Android Chrome has the visibilitychange event; example code is here: http://output.jsbin.com/rinece

To test:

  • on Android Chrome open that link
  • Either
    1. watch the log below the clear button and notice the delay times (so you can see exactly when the event occurred within the page).
    2. or attach the debugger and watch the console
    3. or if you can't attach the debugger (WebView or AOSP) then open http://output.jsbin.com/rinece#http://localhost:80/ and use a proxy or set up a localhost server that shows you the body content (the log text is in the body of the xmlhttp requests; change the # url to a proxy or server where so you can see the Requests occur).
  • Change tabs
  • Watch the log to confirm which events occur on visibilitychange

AOSP (and WebView for Android < 4.4) may have different behaviour than Chrome...

The visibilityChange event is now well supported on mobile - see http://caniuse.com/#search=visibility but beware that it is not supported by iOS UIWebView (even if on iOS9).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM