Не удалось показать предупреждение на popstate

avatar
Vaibhav Mandlik
9 августа 2021 в 06:18
164
1
0

Я реализовал тестовый онлайн-модуль, в котором я хотел предупредить пользователя и получить подтверждение от пользователя для действия кнопки "Назад" в браузере. Но почему-то я не могу этого добиться. Ниже приведен код, который я пытаюсь выполнить:

.
$(function() {
        window.history.pushState({
            page: 1
        }, "", "");
        history.back();
        history.forward();
        window.onpopstate = function(event) {
            if (event) {
                e.preventDefault(); // I entered this just in thought to stop the loading of page so that my alert will be displayed, but it failed
                swal.fire({
                    title: 'This action will terminate your ongoing test and you won\'t be able to attempt the test',
                    text: "Do you still want to continue",
                    type: "warning",
                    showCancelButton: true,
                    confirmButtonText: 'Yes',
                    cancelButtonText: 'No',
                    allowOutsideClick: false
                }).then((result) => {
                    if (result.dismiss != 'cancel') {
                        window.location.href="tests.php";
                    }
                });
            }
        }
    });

РЕДАКТИРОВАТЬ: Я попытался изменить код, и это сработало, но теперь alert отображается при каждой загрузке страницы. Как я могу предотвратить всплывающее предупреждение при загрузке страницы? Ниже приведен код, который я изменил:

.
window.history.pushState({
            page: 0
        }, "", "");
        history.back();
        window.onpopstate = function(event) {
            history.forward();
            if (event) {
                event.preventDefault();
                swal.fire({
                    title: 'This action will terminate your ongoing test and you won\'t be able to attempt the test',
                    text: "Do you still want to continue",
                    type: "warning",
                    showCancelButton: true,
                    confirmButtonText: 'Yes',
                    cancelButtonText: 'No',
                    allowOutsideClick: false
                }).then((result) => {
                    if (result.dismiss != 'cancel') {
                        window.location.href="tests.php";
                    }
                });
            }
        }

Я взял эту ссылку на код отсюда. С кодом в этом ответе я не могу alert пользователя. Может, кто-нибудь скажет мне, где я ошибаюсь? Или как я могу достичь этой функциональности? Приветствуется любая помощь.

Источник

Ответы (1)

avatar
Vaibhav Mandlik
16 декабря 2021 в 07:26
0

Я попытался управлять alert с помощью приведенного ниже кода. Это сработало как-то после нескольких исследований. Если это неправильно, пожалуйста, поправьте меня. Ниже приведен код, который работал у меня:

window.history.pushState({
        page: 0
    }, "", "");
    history.back();
    $(document).on('load', function()) {
    window.onpopstate = function(event) {
        history.forward();
        if (event) {
            event.preventDefault();
            swal.fire({
                title: 'This action will terminate your ongoing test and you won\'t be able to attempt the test',
                text: "Do you still want to continue",
                type: "warning",
                showCancelButton: true,
                confirmButtonText: 'Yes',
                cancelButtonText: 'No',
                allowOutsideClick: false
            }).then((result) => {
                if (result.dismiss != 'cancel') {
                    window.location.href="tests.php";
                }
            });
        }
        }
    }