0

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>
Community
  • 1
  • 1
Johnathon64
  • 1,280
  • 1
  • 20
  • 45
  • ["*This event fires when a window is about to unload its resources. The document is still visible and the event is still cancelable.*"](https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload) So it fires when you're closing the window, if you are still viewing the page. It should not fire if you are viewing another page when it closes. –  Sep 30 '15 at 22:23
  • 2
    This is one of the event handlers that I would **not** declare inside a `document.ready()` since you want to attach it to the window as soon as possible. – Dave Sep 30 '15 at 22:31
  • 1
    Note that the prompt will not show unless you return a non-void (non-null/undefined) value. Your SaveDashboard function doesnt return anything, though your break point should be hit in either case – Patrick Evans Sep 30 '15 at 22:32

1 Answers1

0

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.

taxicala
  • 21,408
  • 7
  • 37
  • 66