RSS

How to run a script when user close the browser

29 Oct

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: , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: