Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I cancel location.href in Javascript

It might sound silly, but I need this functionality.

Can I somehow cancel location.href = 'url' in Javascript once it is executed?

For example on click of button I am changing current page with some resource intensive page, I want to give an option to user so that one can cancel it if next page is going to take long time to load.

like image 937
Software Enthusiastic Avatar asked Oct 15 '25 15:10

Software Enthusiastic


1 Answers

Yes you can. You can use the beforeunload event to display an alert that the user can confirm or cancel. When the user cancels it, the page navigation is canceled.

Example:

window.addEventListener('beforeunload', (event) => {
  // Cancel the event as stated by the standard.
  event.preventDefault();
  // Chrome requires returnValue to be set.
  event.returnValue = '';
});

Note that not all browsers implement this the same way, and Chrome requires you to set the returnValue property on the event to trigger the alert even though the HTML spec says that you should call event.preventDefault() to trigger it.

like image 146
Prutswonder Avatar answered Oct 17 '25 05:10

Prutswonder