Reputation: 4665
I am trying to post data when user arrives my page. This works in chrome and explorer, and also firefox, but however, on firefox, it strangely only works if user closes the page. If they go back, or goes another site (by typing to address bar or whaever) it doesnt post the data. My question is, what is the correct way to use onbeforeunload to post data ?
$(window).bind('beforeunload', function () {
$.post("track.php", {
async: false,
ip: ip,
referer: referer,
clicks: kactane2,
scrolls: kactane,
time: time,
refid: refid,
country: country,
});
});
Upvotes: 3
Views: 1416
Reputation: 3335
There isn't a good way because that is not how onbeforeunload
was meant to be used.
The correct way to use onbeforeunload
is to listen for this event and then unload any data or resources you might be using because the user is leaving the page. You should not use it to try to start new things. According to the HTML5 specification showModalDialog()
, alert()
, confirm()
and prompt()
are explicitly not allowed and the idea is to give you a moment to clean up any event handlers, web workers and other stuff cleanly.
If an event handler is defined then the user may be presented with a page that says "Are you sure you want to leave?"
but for security reasons the form is generally not able to be customized, but it depends on the browser.
You will probably be better off setting the data in a cookie or something that can be done quickly and that is only occurring in the browser, then just look for that data on the next page load.
Upvotes: 2