'onbeforeunload not always working

I'm making a simple script to save some data on when a user access a page and leaves a page, along with some other page details. The script "works", but it doesn't work all the time. It seems to be working sporadically. I'm not getting console errors on the time it doesn't. The server side works fine.

window.onload = function() {


var timeStarted, i, c, l, timeLeft, pageData; 

timeStarted = new Date().getTime();

i = <?php echo $model->id; ?>;
c = <?php echo $model->cat; ?>;
l= <?php echo $model->loc; ?>;

window.onbeforeunload = function(){

timeLeft = new Date().getTime();

pageData = [{name: 'timeStarted', value: timeStarted}, 
            {name: 'i', value: job},
            {name: 'c', value: cat},
            {name: 'l', value: loc},
            {name: 'timeLeft', value: timeLeft}];

// Set url for JavaSCript
var url = '<?php echo Yii::app()->createUrl("item/viewedItemInformation"); ?>';

<?php echo CHtml::ajax(array(
        'url'=>'js:url',
        'data'=> "js: pageData",
        'type'=>'post',
        'dataType'=>'json',
        )); ?>;             
}
}

Note

I've just read this post window.onbeforeunload not working in chrome and I am using chrome. However I seem to get the same results in FF too.

What is the correct away about solving this?

Update I literally couldn't tell you what the situations it does and doesn't work. I am only using this function on item pages. Sometimes when i click on an item page and leave to visit another item it works other times it doesn't it really is that sporadic. What I can say is if I leave the item page for a non item page like the home page, no records are ever recorded.



Solution 1:[1]

onbeforeunload event is fired only if there was ANY interaction of the user with the site. Without ANY interaction event(e.g. click. and not including hover) on your page, onbeforeunload won't be fired.

Solution 2:[2]

You may be able to use setTimeout to delay the tab from closing to do an AJAX request though if it's more than about 50 milliseconds most people will notice and will potentially avoid visiting your site.

The problem I think you're encountering is when the client's browser or operating system stop responding/working. To get 100% of the data in any situation would be extremely difficult if not outright impossible.

That being said you have not clarified what you think the situations are where the onbeforeunload event is not working so you've left your question too open to subjectivity. If you update your question and then comment on my answer I'll be happy to revise it in order to be more specific.


Things to try testing...

1.) Click a local link (a link on your site to another page on your site).

2.) Click an external link.

3.) Close the tab.

4.) Close the window.

5.) Kill the browser process via the task manager/equivalent.

6.) Pull the plug on the computer to emulate a power outage.


According to Mozilla Dev Network...

Since 25 May 2011, the HTML5 specification states that calls to 
window.showModalDialog(), window.alert(), window.confirm(), and window.prompt()
methods may be ignored during this event.

https://developer.mozilla.org/en-US/docs/Web/API/Window.onbeforeunload

So keep in mind that those methods may not work in some browsers when onbeforeunload is supported. In that case you can try to ping the server with an AJAX request and just watch your Apache access log for the request, usually you could send the JavaScript object/data/text/etc as an HTTP query such as request.php?q=javascript-object for example so you can visually confirm if the browser is doing what you think/want it to do.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2