Requirement: If the user's exam answer page is disconnected from the network, a pop-up window needs to prompt the user to check the network
1. navigator.onLine
In the case of networking, it returns true
if (navigator.onLine) {
console.log('网络已连接');
} else {
console.log('已断网');
}
2. window.addEventListener()
Actively monitor the current network connection status
window.addEventListener('online', function() {
console.log('网络已连接');
});
window.addEventListener('offline', function() {
console.log('已断网');
});
Note: There are compatibility issues on Apple computers, and the monitoring is invalid
3. A more compatible way of writing
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() {
console.log("联网");
});
EventUtil.addHandler(window, "offline", function() {
console.log("断网");
});