Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 209
fadedbee Avatar asked Feb 22 '12 11:02

fadedbee


2 Answers

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"); }
like image 186
Jan Jongboom Avatar answered Sep 21 '22 23:09

Jan Jongboom


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.

like image 43
Tom van der Woerdt Avatar answered Sep 21 '22 23:09

Tom van der Woerdt