How to detect if browser is in the process of loading a new page
Asked Answered
A

2

8

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.

Azobenzene answered 22/2, 2012 at 11:21 Comment(0)
L
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"); }
Larose answered 22/2, 2012 at 11:25 Comment(0)
I
2

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.

Isoprene answered 22/2, 2012 at 11:24 Comment(2)
Yeah, agree. There is no way to check.Reynolds
Thanks, but that's not negotiable.Azobenzene

© 2022 - 2024 — McMap. All rights reserved.