知向前端
html5+js 监听网络在线与离线?
2016-10-9 Jon
html5+js 监听网络在线与离线



<!DOCTYPE html>

<html lang="en">

<head>

  <meta charset="UTF-8">

  <title>html5+js 监听网络在线与离线</title>

</head>

<body>

  <script src="http://libs.baidu.com/jquery/1.9.1/jquery.min.js"></script>

  <script>

    // 自动重连代码

    var isIE=navigator.userAgent.indexOf("MSIE")>0?true:false; //判断是否是IE浏览器

    var isFirefox=navigator.userAgent.indexOf("Firefox")>0?true:false;//是否是火狐浏览器

    if(isIE || isFirefox){

      setInterval(function() {

        ajaxLun();

      }, 5000);

    }else{

      // 非 IE 火狐

      window.addEventListener('online', anewLink, false);

      // window.addEventListener('offline', offline, false);

    }

    var isLine = 0;

    function ajaxLun(){

      $.ajax({

        type: 'get',

        url: '自己的请求地址',// 可以换成自己网站的url

        dataType: 'json',

        success: function(datas){

          if(isLine){

            isLine = 0;

            // 执行重连的方法

            anewLink();

          }

        },

        error: function(xml,err){

          if(!isLine){

            isLine = 1;

          }

        }

      });

    }

    // 断网后重连

    function anewLink(){

      console.log('重新连接。。。');

      // 执行重新连接需要的代码

    }

  </script>

</body>

</html>

<!--

  一些参考 demo......

  <!doctype html>

  <html>

  <head>

  <meta http-equiv="content-type" content="text/html;charset=utf-8">

  <title>html5 js 监听网络在线与离线</title>

  </head>

  <body>

  <div id="status" style="font-size:100px;"></div>

  <script type="text/javascript" language="javascript" charset="utf-8">

      $$ = function(id){return document.getElementById(id);};

      if(navigator.onLine){

          $$("status").innerHTML="第一次加载时在线";

      } else{

          $$("status").innerHTML="第一次加载时离线";

      }

      window.addEventListener("online", online, false);

      function online(){

          $$("status").innerHTML="on";

      }

      window.addEventListener("offline", offline, false);

      function offline(){

          $$("status").innerHTML="off";

      }

  </script>

  </body>

  </html>

 -->






发表评论:
昵称

邮件地址 (选填)

个人主页 (选填)

内容