In many scenarios, web applications can be started only when machines are connected to IOT platform. If the network is not connected, an error is prompted. ,
However, the machine sometimes needs to be restarted. If the web application is started immediately after the machine is restarted, the network service on the machine may not be ready yet.
Especially in Windows 7, it takes several seconds to start the network service. What should I do at this time?
I have tried several methods before:
For example, ping is used, but ping requires a non-local IP address. This is not very common
For example, monitoring whether a port is in use but the optical port is in use does not indicate that the network has been started.
On the other hand, if it is a web application, it is better to judge at the front end, such as using javascript.
Some people on the Internet also write javascript ping simulation results. But it is a little troublesome.
What should we do? The key point is that html5 can provide a good solution:
Method 1:
Navigator. onLine
Copy codeThe Code is as follows:
If (navigator. onLine)
{// Working properly}
Else {// task for executing the offline status}
The new features of html5 navigator can be easily solved.
HTML5 defines a navigator. onLine attribute for this purpose. If the attribute value is true, the device can access the internet. If the value is false, the device is offline.
Of course different browsers have different support for this.
IE6 + and Safari 5 + support better
Firefox 3 + supports the navigator. onLine attribute, but you must manually select the menu item "file-Web Developer (settings)-offline work" to make the browser work normally.
Chrome requires more than 12.
Method 2:
Of course, if you want to support better compatibility, you can use the following two events: online and offline. When the network changes from offline to online or from online to offline, these two events are triggered respectively. These two events are triggered on the window object.
To check whether the application is offline, you are advised to obtain the initial status through navigator. onLine after loading the page. The preceding two events are used to determine whether the network connection status changes. When the preceding event is triggered, the value of the navigator. onLine attribute changes. However, you must manually poll this attribute to detect changes in the network status.
Copy codeThe Code is as follows:
Var EventUtil = {
AddHandler: function (element, type, handler ){
If (element. addEventListener ){
Element. addEventListener (type, handler, false );
} Else if (element. attachEvent ){
Element. attachEvent ("on" + type, handler );
} Else {
Element ["on" + type] = handler;
}
}
};
EventUtil. addHandler (window, "online", function (){
Alert ("Online ");
});
EventUtil. addHandler (window, "offline", function (){
Alert ("Offline ");
});