使用JS在浏览器中判断当前网络连接状态的几种方法

JavaScript06

使用JS在浏览器中判断当前网络连接状态的几种方法,第1张

通过navigator.onLine判断当前网络状态:

if(navigator.onLine){

...}else{ ...}

非常简单,但是并不准确-根据MDN的描述:

navigator.onLine只会在机器未连接到局域网或路由器时返回false,其他情况下均返回true。

也就是说,机器连接上路由器后,即使这个路由器没联通网络,navigator.onLine仍然返回true。

 if (navigator.onLine) {

         alert("正常工作")

      } else {

       alert("掉线了")

      }

//vue项目跳转其他项目

window.location.href=你想跳转的地址链接

JavaScript 的document对象中有一个location的子对象,其包括是属性如下:document.location.host //表示当前域名 + 端口号document.location.hostname //表示域名document.location.href //表示完整的URLdocument.location.port //表示端口号document.location.protocol //表示当前的网络协议所以通过上面第五条就能判断当前的网络协议了,具体判断如下:[javascript] view plain copyvar protocolStr = document.location.protocolif(protocolStr == "http"){console.log("protocol = " + protocolStr)}else if(protocolStr == "https"){console.log("protocol = " + protocolStr)}else{console.log("other protocol")}