I have a script on multiple domains that are not mine which sends data to an AWS SQS queue on page exit. When I compare the number of times I receive data to the number of times that the script is loaded on the page I show that 57% of time I do not receive data. I'm expecting to not receive data maybe 10 - 20% of the time which would be acceptable. The data is capturing user actions so I can not send any earlier than leaving the page. I'm wondering if I am doing something obviously wrong in my code. Any help is greatly appreciated.
function addEvent(){
var myEvent = window.attachEvent || window.addEventListener;
var chkevent = window.attachEvent ? 'onbeforeunload' : 'beforeunload'; /// make IE7, IE8 compitable
myEvent(chkevent, function(e) { // For >=IE7, Chrome, Firefox
if(e || window.event){
pageUnload();
}
});
}
addEvent();
function pageUnload(){
var host = window.location.host;
var path = window.location.pathname;
window.parent.data = '';
for (var i = 0; i < arrayCount; i++){
for (var j = 0; j < dataArray[i].length; j++){
window.parent.data += dataArray[i][j];
}
}
var urlString = 'h='+host+'&p='+path+'&'+window.parent.data;
var url = 'http://www.AWS_SQS_QUEUE.com?Action=SendMessage&MessageBody='+encodeURIComponent(urlString);
var method = 'HEAD';//Changed from GET to HEAD to avoid Cross Domain blocking in FF
if (navigator.sendBeacon) {
navigator.sendBeacon(url, null);
}
else{
var xhr = new XMLHttpRequest();
if("withCredentials" in xhr) {
xhr.open(method, url, true);
}
else if (typeof XDomainRequest != "undefined"){
xhr = new XDomainRequest();
xhr.open(method, url);
}
else {
xhr = null;
}
if (!xhr){
return;
}
xhr.send();
}
}