How to check if user left the window

10

I would like to know a way to check if the user exited the window of my page with Javascript, for example, if he switched tab (to search for something in Google for example) the script changes the window title to another title that I define ..

    
asked by anonymous 09.03.2014 / 00:04

3 answers

9

I think you can use the event blur

Example using simple javascript:

window.addEventListener('blur', function(){
    // correr codigo aqui
});

In the example in addition to triggering the event in the window change, when you focus on the address bar it fires too.

EDIT:

I add more info after a good question from @ JoãoParaná :

In Safari / IOS the blur event does not fire. In this case the pagehide must be used. You may need to use both if necessary:

window.addEventListener('blur', correrEstaFuncao);
window.addEventListener('pagehide', correrEstaFuncao);

Demo

    
09.03.2014 / 00:09
3

The new HTML5 api Page Visibility API does exactly what you're asking for:

if(document.hidden !== undefined){
    document.addEventListener("visibilityChange", acao, false);   
}

function acao(){
    console.log("O estado da janela mudou!");
}

Example: FIDDLE

    
10.03.2014 / 18:08
1

Some time ago I looked for a script that did just that.

It adds listeners to various types of browsers. Calling the functionHidden function when the page loses focus. And functionVisible when the page returns to "focus".

(function () {
    var hidden = "hidden";
    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);
    else if ('onfocusin' in document) document.onfocusin = document.onfocusout = onchange;
    else window.onpageshow = window.onpagehide = window.onfocus = window.onblur = onchange;

    function onchange(evt) {
        var evtMap = {
            focus: true,
            focusin: true,
            pageshow: true,
            blur: false,
            focusout: false,
            pagehide: false
        };

        evt = evt || window.event;
        if (evt.type in evtMap) evtMap[evt.type] ? functionVisible() : functionHidden();
        else this[hidden] ? functionHidden() : functionVisible();
    }

    function functionVisible() {
        console.log('Visible');
    }

    function functionHidden() {
        console.log('Hidden');
    }
})();

This script maps the events of almost all browsers.

You can test it on jsfiddle by looking at the console.

    
10.03.2014 / 17:44