Can I cancel location.href in Javascript

后端 未结 2 1878
误落风尘
误落风尘 2021-01-20 02:35

It might sound silly, but I need this functionality.

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

For ex

相关标签:
2条回答
  • 2021-01-20 02:54

    What @Prutswonder suggest is the only way to take action BEFORE the page is unloaded. The new page cannot be loaded before the old page is unloaded. This is the most common/straight forward solution.

    If you do NEED to load the new page while you are still in the current page you could use frames/iframes.

    Take a page with 2 iFrames on top of each other.

    The page has control over the 2 inner frames => the inner frame can notify the page that is has been fully loaded. (in the onLoad event) And if it's loaded the page can put that iFrame on top.

    The page can abort the loading if the user decides to. Leaving the loading iFrame on the bottom.

    0 讨论(0)
  • 2021-01-20 03:11

    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.

    0 讨论(0)
提交回复
热议问题