Home > Article > Web Front-end > Implementation code for javascript detection of Internet access_javascript skills
The simplest and crudest way is to load network resources, JS files or image files.
Use jQuery variables to detect whether you are connected to the Internet
function doConnectFunction() { return true; } function doNotConnectFunction() { return false; } var i = new Image(); i.onload = doConnectFunction; i.onerror = doNotConnectFunction; i.src = 'http://su.bdimg.com/static/superplus/img/logo_white.png?d=' + escape(Date());
The problem with loading network resources is the detection of the Internet. If it is a LAN detection, there is nothing you can do.
At this time, we need a better solution, so we need to use navigator.onLine. The disadvantage of this attribute is that it is compatible with browsers. Chrome and Safari all support it perfectly, and IE7 and above are supported. Firefox and IE6 are more pitiful. They only return false when the browser is "offline", and return true otherwise. It is true even if the network cable is pinched, but Opera no longer supports it.
So we have to add a compatibility method: send an http header request to the location.hostname address, the code is as follows:
var xhr = new ( window.ActiveXObject || XMLHttpRequest )( "Microsoft.XMLHTTP" ); var status; xhr.open( "HEAD", "//" + window.location.hostname + "/?rand=" + Math.floor((1 + Math.random()) * 0x10000), false ); try { xhr.send(); return ( xhr.status >= 200 && xhr.status < 300 || xhr.status === 304 ); } catch (error) { return false; }
One thing to note is that the third parameter of the open method must be passed false, and it must be a synchronous request.
Summary: If the browser supports navigator.onLine, use navigator.onLine. If it does not support it, send an http header request.
Original article, please indicate when reprinting: Reprinted from Front-end Development