Categories
JavaScript Answers

How to prevent a webpage from navigating away using JavaScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *