简体   繁体   中英

onbeforeunload function fires on browser back button

We´re using following code to show a loading-modal if the loading of next page takes to long.

window.onbeforeunload = function () {
    window.setTimeout(showLoader, 2000);
}

function showLoader() {
    var loader = '<div id="layoutLoadingModal" class="modal fade" role="dialog">' +
        '<div class="modal-dialog">' +
            '<div class="modal-content">' +
                '<div class="modal-body">' +
                    '<h1>Loading!</h1>' +
                '</div>' +
            '</div>' +
        '</div>' +
    '</div>';
    $("body").append(loader);
    $('#layoutLoadingModal').modal('show');
}

Unfortunately it also shows the modal if the user uses the browser back button or a button with history.go(-1); Is there any way to tweek the code to prevent this?

*edit This script is present on both pages. When i am on the "second page" and click back. The script on the second page isn´t firing because the loadtime is less than 2s. But the script is firing when the previous page is loaded, even though it shouldn´t. So the first page shows the Loading-modal from scratch, and you have to click somewhere on the page to close it.

Ok, It turned out I had interpered the situation wrong. When I´m leaving the starting page, the loading-modal will show, at least if it is taking more than 2s to load the second page. When i click the back button, the browser is showing me the starting page in its end state with the Loading-modal showing.

So when I added

window.onunload = function () {
    $('#layoutLoadingModal').modal('hide');
}

it all works as expected.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM