0

Possible Duplicate:
javascript detect browser close tab/close browser

I am doing a real time game site in php, I wish to call a function on closing the browser, how can i detect closing the browser using php or javascript ? I have tried using onbeforeunload and onunload events, but found that these events are triggered even if the window is refreshed or navigates using back button, forward button etc.. And also these events are not working well in all popular browsers. Is there any posible way to detect only the window close event which performs well in all browsers?

Thanks in advance

4
  • Is it just the closing of that page or closing the entire browser? Commented Oct 11, 2012 at 10:27
  • try searching this on stackoverflow, there are several instances of similar questions. There is no way to detect a browser close event. I had a similar challenge. I used a cronjob to update the database for the user status by checking the session (expires on idle for 10 mins.) Commented Oct 11, 2012 at 10:33
  • Its just to close the window not the browser Commented Oct 11, 2012 at 10:37
  • @chinju: do you mind editing your question's description. You asked for browser close event, now you want only window/tab close and not browser close...!! Commented Oct 11, 2012 at 10:43

1 Answer 1

2

You can set a session in PHP (with a timeout) that is set to 1 when you visit the website and have an Ajax function that runs a task every 20 seconds that calls a function that sets the session to 1 again.

When the user closes the browser and the Ajax call no longer runs the session will time out and set to 0/null. So when you revisit the site the session will be 0 and you can then redirect/do what you want with the user.

 setInterval(function(){ $.ajax({ url: '/', success: function(){ //do stuff with data //Like send a POST/GET that //if isset sets the session 1 again } }); }, 20000); 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.