Cross-browser: detect blur event on window

后端 未结 6 2340
挽巷
挽巷 2021-02-08 03:24

I just read, I think all the thread that deals with this subject, and I can\'t find a real solution to my problem. I need to detect when the browser window loses its focus, i.e.

6条回答
  •  花落未央
    2021-02-08 04:03

    Here is an alternative solution to your question but it uses the Page Visibility API and Solution is Cross Browser compatible.

    (function() {
        var hidden = "hidden";
    
        // Standards:
        if (hidden in document)
            document.addEventListener("visibilitychange", onchange);
        else if ((hidden = "mozHidden") in document)
            document.addEventListener("mozvisibilitychange", onchange);
        else if ((hidden = "webkitHidden") in document)
            document.addEventListener("webkitvisibilitychange", onchange);
        else if ((hidden = "msHidden") in document)
            document.addEventListener("msvisibilitychange", onchange);
        // IE 9 and lower:
        else if ("onfocusin" in document)
            document.onfocusin = document.onfocusout = onchange;
        // All others:
        else
            window.onpageshow = window.onpagehide = window.onfocus = window.onblur = onchange;
    
        function onchange(evt) {
            var v = "visible",
                h = "hidden",
                evtMap = {
                    focus: v,
                    focusin: v,
                    pageshow: v,
                    blur: h,
                    focusout: h,
                    pagehide: h
                };
    
            evt = evt || window.event;
            if (evt.type in evtMap) {
                console.log(evtMap[evt.type]);
            } else {
    
                console.log(this[hidden] ? "hidden" : "visible");
            }
        }
    
        // set the initial state (but only if browser supports the Page Visibility API)
        if (document[hidden] !== undefined)
            onchange({
                type: document[hidden] ? "blur" : "focus"
            });
    })();
    

提交回复
热议问题