最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

dom events - Can I cancel location.href in Javascript - Stack Overflow

programmeradmin4浏览0评论

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.

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.

Share Improve this question edited Aug 26, 2019 at 16:08 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Mar 19, 2010 at 7:42 Software EnthusiasticSoftware Enthusiastic 26.5k17 gold badges60 silver badges68 bronze badges 2
  • 1 Do you mean you want to be able to see if the page is taking a long time to load, and then cancel? – Tim Goodman Commented Mar 19, 2010 at 8:02
  • What happens is event after location.href execution, and widnow.onbeforeunload current page remains visible until next page is loaded. User can cancel next page load by pressing Escape Key in the keyboard. I want this functionality using javascript. – Software Enthusiastic Commented Mar 19, 2010 at 10:21
Add a ment  | 

2 Answers 2

Reset to default 6

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.

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 mon/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)

  1. 暂无评论