Vaggelis
Vaggelis

Reputation: 1011

onbeforeunload event exception?

i am wondering if there is a way to make onbeforeunload event alert be triggered with any other case except a specific function induced page reload.

most of the previously answered questions are at best 3 years old.

window.addEventListener('beforeunload', function (e) {

e.preventDefault();

e.returnValue = '';

});

document.getElementById("reload").addEventListener("click", myFunction);

function myFunction() {

location.reload();

}  // I WANT TO EXCLUDE THIS FUNCTION FROM ONBEFOREUNLOAD EVENT ALERT
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
</head>
<body>
<button id="reload">RELOAD FROM HERE SHOULD NOT TRIGGER ONBEFOREUNLOAD ALERT</button>
</body>
</html>

Upvotes: 0

Views: 648

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370999

A simple solution would be to set a flag, and check that flag in the beforeunload listener:

let beforeUnloadAlert = true;
window.addEventListener('beforeunload', function (e) {
  if (!beforeUnloadAlert) return;

  // etc
  e.preventDefault();
  e.returnValue = '';
});
function myFunction() {
  beforeUnloadAlert = false;
  location.reload();
}

Another approach would be to remove the listener just before calling .reload, by putting the listener in a named function:

window.addEventListener('beforeunload', unloadHandler);
function myFunction() {
  window.removeEventListener('beforeunload', unloadHandler);
  location.reload();
}

Upvotes: 1

Related Questions