I have an onbeforeunload event which should fire when I leave the page and run the code I have attached to that event. I have placed this within the scripts tag of the cshtml in my page, so in theory it should only fire if I am on that particular page and move off it(my understanding of the event could be incorrect). However when I go to another page the onbeforeunload event does not seem to want to fire. I have tried setting a breakpoint on it but does not seem to hit it and am not getting any errors on my console in firebug.
I have looked at this post which one of the posters mentioned using this event to detect a page change Best way to detect when a user leaves a web page?
<script type="text/javascript">
$(document).ready(function () {
window.onbeforeunload = SaveDashboard;
});
function SaveDashboard(){
var gridArray = _.map($('.grid-stack .grid-stack-item:visible'), function (el) {
el = $(el);
var gridID = el.find('.grid-stack-item-content.ui-draggable-handle').first().attr('id');
var node = el.data('_gridstack_node');
return {
id: gridID,
x: node.x,
y: node.y,
width: node.width,
height: node.height
};
});
$.ajax({
url: 'Dashboard/EditWidgets/',
type: 'PUT',
data: {
widget: gridArray
},
success: function (dataset) {
},
failure: function (xhr, error) {
console.log(xhr)
console.log(error)
},
});
}
</script>
you should return a string in the onbeforeunload
handler. if you don't return anything, the event won't fire your handler. the text you have to return is the text that will be placed in the prompt the browser will open asking if the user really wants to leave the page.