Prevent a webpage from navigating away using JavaScript

Software Enthusiastic picture Software Enthusiastic · May 4, 2009 · Viewed 128.3k times · Source

How to prevent a webpage from navigating away using JavaScript?

Answer

Jimmie R. Houts picture Jimmie R. Houts · May 4, 2009

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

window.onbeforeunload = function() {
  return "";
}

Note: An empty string is returned because newer browsers provide a message such as "Any unsaved changes will be lost" that cannot be overridden.

In older browsers you could specify the message to display in the prompt:

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