How to identify that the user is in the page of my site with Jquery

3

I'm making a script to identify if the user is on the site or not, but I have no idea how to do this, could anyone help me?

My question is the following, I want to know if the user is on my page, for example if the user goes to another tab as if he had left, if he goes back to the tab of my site, he will be back on the site.

I'm using PHP.

    
asked by anonymous 11.04.2015 / 16:10

1 answer

0

Depending on the answer from SOen you can use Page Visibility API that allows you to detect if a page is hidden.

Browsers that support:

  • Chrome 13 +
  • Internet Explorer 10 +
  • Firefox 10 +
  • Opera 12.10+ [ Notes ]

The following code makes use of the API and also tries to provide similar functionality for some browsers with no compatibility.

(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]);//Troque aqui pelo ajax
    else
      console.log(this[hidden] ? "hidden" : "visible");//Troque aqui pelo ajax
  }

  // set the initial state (but only if browser supports the Page Visibility API)
  if( document[hidden] !== undefined )
    onchange({type: document[hidden] ? "blur" : "focus"});
})();

onfocusin and onfocusout are required for IE9 and older , while that all others use onfocus and onblur , except for iOS, which uses onpageshow and onpagehide .

Where% s are% s change to an Ajax that will notify the server that the user left or entered the page.

    
11.04.2015 / 16:29