How to prevent a webpage from navigating away using JavaScript?

Sometimes, we want to prevent a webpage from navigating away using JavaScript.

In this article, we’ll look at how to prevent a webpage from navigating away using JavaScript.

How to prevent a webpage from navigating away using JavaScript?

To prevent a webpage from navigating away using JavaScript, we can set the window.onbeforeunload property to a function that returns any value.

For instance, we write

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

to set window.onbeforeunload to a function that returns an empty string to interrupt navigation with an alert box when we try to navigate to a different page.

Conclusion

To prevent a webpage from navigating away using JavaScript, we can set the window.onbeforeunload property to a function that returns any value.