0

I am trying to send a post to my server when a user either closes their browser or closes a window.

This is what I have so far:

 $(window).unload(function(){
    $.post('/offline', {account_id: ACCOUNT_ID});
});

However, this only seems to work when a user enters a new url in the current window.

In addition to whenever a user enters a new url in a window, I need to send a post to the server when the browser or window is closed.

Anyone know what the problem is?

Thank you.

Update:

I think the above javascript will work for me, however, this occurs for every event on the website. For example, clicking a link.

Is it possible to to only trigger this if a user enters a new url or closes the window?

Brian
  • 5,951
  • 14
  • 53
  • 77

4 Answers4

1

The problem is, when the browser is shut down you have a very limited amount of means of interrupting that action. There are many reasons why that such an event would be impossible to trap - say they lose power or network connectivity - your post would never work. I suggest rethinking your need to capture this, and going about the problem you're trying to solve in a different manner.

Jake Feasel
  • 16,785
  • 5
  • 53
  • 66
  • so is it possible to make a post when the browser is not close, but the window for the website is closed? – Brian Dec 08 '11 at 07:07
  • +1 I believe the reason for posting on window close, is pure statistical, which page makes the user leave site, which page has the user "played" on, etc. –  Dec 08 '11 at 07:07
  • See the limitations of beforeunload discussed here: http://stackoverflow.com/questions/6063522/jquery-beforeunload – Jake Feasel Dec 08 '11 at 07:11
  • And note that while you "can run a function as the page is unloading" - an ajax post is a relatively slow thing, and unlike to get very far before the window is destroyed. FYI. – Jake Feasel Dec 08 '11 at 07:13
  • I am utilizing ironworker for ruby. I just need a quick post to start the background worker. – Brian Dec 08 '11 at 07:19
0

This approach will not work as when browser is closed, your ongoing request will be interrupted.

Instead you should define a setInterval method in which you will continue to ping the server after specific interval and on the server side, if you didn't receive ping for specific time, user will be treated as logged off.

Ghazi
  • 966
  • 8
  • 15
0

you can use

$(window).bind("beforeunload", function()

possibally duplicate of How to capture the browser window close event?

Community
  • 1
  • 1
Hemant Metalia
  • 29,730
  • 18
  • 72
  • 91
0
window.onbeforeunload = function (e) {
var message = "Your confirmation message goes here.",
e = e || window.event;
// For IE and Firefox
if (e) {
e.returnValue = message;
}

// For Safari
return message;
};
Babu
  • 127
  • 2
  • 9