Recently, the backstage management system of the company raised this demand, so I collected some methods from the Internet, and now record them for convenient reference in the future.
First I’ll post the requirements
No more nonsense, directly on the code, this project is based on vue.js
mouted () {
this.checkNetwork()
Copy the code
},
methods: {
CheckNetwork () {const that = this const 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(e) { if (e.type === 'online') { that.network = true } else { that.network = false } }) EventUtil.addHandler(window, 'offline', function(e) { if (e.type === 'offline') { that.network = false } else { that.network = true } })Copy the code
}
After testing, this method is effective.
In addition, several methods provided on the Internet are attached, but I did not go to test, interested children’s shoes can try
1, the navigator. OnLine
If (navigator.online) {... } else {... // Work offline}Copy the code
Navigator. onLine will only return false if the machine is not connected to a LAN or router, and true in all other cases.
Ajax polling
setInterval (function() {
//Ajax...
Copy the code
}, 1000).
3. Use the IMG onError event
In view of my limited level, if there are mistakes in the code or need to improve the place you are welcome to often come to common communication, if you need to reprint please attach this blog address, thank you.