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

javascript - How to detect if browser is in the process of loading a new page - Stack Overflow

programmeradmin0浏览0评论

I have a web app with some 'safety' code which causes a page reload if the server (Socket.IO) connection goes silent for more than 5 seconds (generally customer site firewall/broken-proxy issues).

The Socket.IO connection stops as soon a new page starts loading, but the safety code doesn't see this. Navigating to a slow page causes the safety code to fire and jump you back to the previous page.

I need to be able to tell (just before this code causes a reload) whether the browser is currently waiting for a new (slow) page to load.

What approaches are there to doing this, other than putting a jQuery click event on every link (which would not catch navigation via the address bar)?

Thanks,

Chris.

I have a web app with some 'safety' code which causes a page reload if the server (Socket.IO) connection goes silent for more than 5 seconds (generally customer site firewall/broken-proxy issues).

The Socket.IO connection stops as soon a new page starts loading, but the safety code doesn't see this. Navigating to a slow page causes the safety code to fire and jump you back to the previous page.

I need to be able to tell (just before this code causes a reload) whether the browser is currently waiting for a new (slow) page to load.

What approaches are there to doing this, other than putting a jQuery click event on every link (which would not catch navigation via the address bar)?

Thanks,

Chris.

Share Improve this question asked Feb 22, 2012 at 11:21 fadedbeefadedbee 44.8k48 gold badges199 silver badges348 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 15

Monitoring window.onbeforeunload would do the trick. Fires right after the user starts navigating away.

Try typing this in the Chrome Console on any page and click on any link:

window.onbeforeunload = function () { console.log("oh noes"); }

My recommendation: fix your code so that you don't reload the page when the socket disconnects. Problem solved.

Edit
I suppose you could simply set a variable such as isReloading when the page reloads. You'd need to monitor onbeforeunload as well, and check what happens first: disconnect or the unload event. If the disconnect happens first, you're getting disconnected. Trigger the isReloading flag and reload. In the onbeforeunload check whether the flag was set. Reverse the concept of checking whether a slow page is loading: check whether you are reloading.

发布评论

评论列表(0)

  1. 暂无评论