Software Enthusiastic Software Enthusiastic - 21 days ago 4
Javascript Question

How do you prevent a webpage from navigating away in JavaScript?

How do you prevent a webpage from navigating away in JavaScript?

Answer

Using onbeforeunload only allows you to display messages, but it will not interrupt the navigation (because it is too late). However, you can use onbeforeunload and it will interrupt navigation:

window.onbeforeunload = function() {
  return "Are you sure you want to navigate away?";
}

Edit: Removed confirm() in return statement as this caused a confirm window as expected, but also showed a second confirm with the result of the first confirm.

Comments