pageShow event in javascript

后端 未结 10 882
不知归路
不知归路 2020-12-10 05:21

I have the following code:



    
    

        
10条回答
  •  时光取名叫无心
    2020-12-10 05:33

    The pageshow event doesn't work in many browsers e.g. if using WebView or UIWebView within an App on mobile.

    Instead you need a four pronged attack:

    1. onfocus occurs when desktop pages and some mobile pages come back to life

    2. pageshow occurs when iOS Safari comes back to life - but not UIWebView

    3. visibilitychange occurs when Windows Mobile IE11 comes back to life - see http://daniemon.com/tech/webapps/page-visibility/ and try http://jsbin.com/runed/4 Edit: Looks like IE11 on WP8.1 now supports the pageshow event.

    4. webkitRequestAnimationFrame detects if page inside Mobile App comes back to focus. Workaround needed because window.focus, visibilitychange and pageshow events don't work in Android apps (WebView) or iOS apps (UIWebView).

    Code might look like:

    window.addEventListener('focus', pageAwakened);
    window.addEventListener('pageshow', pageAwakened);
    window.addEventListener('visibilitychange', function() {
        !document.hidden && pageAwakened();
    });
    if (window.webkitRequestAnimationFrame && (/^iP/.test(navigator.platform) || /Android/.test(navigator.userAgent))) {
        webkitRequestAnimationFrame(webkitWake);
    }
    
    var lastTs;
    function webkitWake(timestamp) {
        if ((timestamp - lastTs) > 10000) {
            pageAwakened();
        }
        lastTs = timestamp;
        webkitRequestAnimationFrame(webkitWake);
    }
    
    function pageAwakened() {
        console.log('awakened at ' + (new Date));
    }
    

    If you wish to support <= IE8 or documentMode <= 8 then need attachEvent for focus.

    Edit: Note that most modern browsers (including desktop IE11 and desktop Edge) support the pageshow event.

提交回复
热议问题