How to reliably send a request cross domain and cross browser on page unload
- by Agmin
I have javascript code that's loaded by 3rd parties. The javascript keeps track of a number of metrics, and when a user exits the page I'd like to send the metrics back to my server.
Due to XSS checks in some browsers, like IE, I cannot do a simple jquery.ajax() call. Instead, I'm appending an image src to the page with jquery. Here's the code, cased by browser:
function record_metrics() {
//Arbitrary code execution here to set test_url
$esajquery('#MainDiv').append("<img src='" + test_url + "' />");
}
if ($esajquery.browser.msie) {
window.onbeforeunload = function() { record_metrics(); }
} else {
$esajquery(window).unload(
function(){ record_metrics(); }
);
}
FF aborts the request to "test_url" if I use window.onbeforeunload, and IE8 doesn't work with jquery's unload(). IE8 also fails to work if the arbitrary test_url setting code is too long, although IE8 seems to work fine if the is immediately appended to the DOM.
Is there a better way to solve this issue? Unfortunately this really needs to execute when a user leaves the page.