RSS

Tag Archives: Required Auto Logout When Browser Closed

How to run a script when user close the browser


I’ve heard that the body element attribute “onbeforeunload” can be used to detect when the window is about to close. You could use ajax to cause a php script to be executed with this attribute. For example:

in this code logout page only call when browser Tab Close .This logout page can’t call on page refresh.

HTML Code:

<html><head>
<script type="text/javascript">
function logout() {
 var xmlhttp=new XMLHttpRequest();
 xmlhttp.open("GET", "logout.php", true);
 xmlhttp.send();
}
</script></head>
<body onbeforeunload="logout()">
Your page here
</body></html>



Second Way:


<html>
<body>

<script type="text/javascript">
function ajaxFunction()
{
var xmlHttp;
try
  {
  // Firefox, Opera 8.0+, Safari
  xmlHttp=new XMLHttpRequest();
  }
catch (e)
  {
  // Internet Explorer
  try
    {
    xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
    }
  catch (e)
    {
    try
      {
      xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
    catch (e)
      {
      alert("Your browser does not support AJAX!");
      return false;
      }
    }
  }
  xmlHttp.onreadystatechange=function()
    {
    if(xmlHttp.readyState==4)
      {
      document.myForm.time.value=xmlHttp.responseText;
      }
    }
  xmlHttp.open("GET","time.asp",true);
  xmlHttp.send(null);
  }
</script>

<form name="myForm">
Name: <input type="text"
onkeyup="ajaxFunction();" name="username" />
Time: <input type="text" name="time" />
</form>

</body>
</html>
Advertisements
 
Leave a comment

Posted by on October 29, 2013 in PHP

 

Tags: , ,