Я реализовал тестовый онлайн-модуль, в котором я хотел предупредить пользователя и получить подтверждение от пользователя для действия кнопки "Назад" в браузере. Но почему-то я не могу этого добиться. Ниже приведен код, который я пытаюсь выполнить:
.$(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
пользователя. Может, кто-нибудь скажет мне, где я ошибаюсь? Или как я могу достичь этой функциональности?
Приветствуется любая помощь.