【问题标题】:JQuery Mobile Detected if there's internet ConnectionJQuery Mobile 检测是否有互联网连接
【发布时间】:2016-03-14 22:05:11
【问题描述】:

通过我的网络应用程序检测我的手机是否有互联网连接的最佳方法是什么?

【问题讨论】:

    标签: javascript html jquery-mobile internet-connection


    【解决方案1】:

    这不需要任何代码——它是 HTML5 API 的一部分。检查window.navigator.onLine 的值——如果用户离线,它将是false

    http://www.whatwg.org/specs/web-apps/current-work/multipage/offline.html#browser-state

    【讨论】:

    • 即使我处于离线状态,这也会使我处于在线状态。 <body onload='updateIndicator()' ononline='updateIndicator()' onoffline='updateIndicator()'> <!--Check internet Connection --> <script><br/> function updateIndicator() { document.getElementById('indicator').textContent = navigator.onLine ? 'online' : 'offline'; } </script> <p>The network is: <span id="indicator">(state unknown)</span> </body>我尝试格式化但不能:(
    • 试试这个:function hasConnection() { if (window.navigator.connection.type === Connection.NONE) { return false; } 返回真; }
    【解决方案2】:

    一个选项可能是changing the Ajax settings 来添加特定的timeout,然后添加一个error 处理程序来查找textStatus(第二个参数)'timeout'

    发生超时时,互联网连接不稳定或您的网站已关闭。


    使用ajaxSetup 为所有请求设置选项默认值:

    $.ajaxSetup({
        timeout: 1, // Microseconds, for the laughs.  Guaranteed timeout.
        error: function(request, status, maybe_an_exception_object) {
            if(status != 'timeout')
                alert("YOU BROKE IT");
            else
                alert("OH NOES TEH INTARWEBS ARE DOWN!!!!!1one");
        }
    });
    

    【讨论】:

    • @Satch,我已经使用我提供的链接为您组装了一个实用但不太有用的示例。 如果您想了解更多信息,我强烈建议您参考文档,因为我在这里所做的一切都是基于文档和我提供的所需任务的描述。
    • 这真的行不通。 window.navigator.onLine 的答案是正确的。
    • @Satch3000 你能告诉我任何工作的例子吗?或者我们如何集中实施?
    【解决方案3】:

    在简单的 JS 代码中可以做到这一点,原因是所有功能设备都不支持 JS 然而,对于基于 Web 的应用程序,这是使用最少的代码

    online = window.navigator.onLine;
    if (navigator.onLine) {
      alert('you are online');
    } else {
      alert('you are offline');
    }
    

    【讨论】:

      【解决方案4】:

      如果您想每隔 X 秒检查一次连接。

              $(document).ready(function() {
                  setInterval(function(){
                      var isOnline = navigator.onLine;
                      if (isOnline) {
                          console.log("Connected");
                      }
                      else {
                          console.log("Not Connected");
                      }
                  }, 30000); // 10000 = 10 seconds, check for connection every 30 seconds
              });
      

      【讨论】:

        【解决方案5】:

        如果你想要比 window.navigator.onLine 更具兼容性、可靠性和可定制性的东西,试试我的 jQuery 插件:http://tomriley.net/blog/archives/111

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2013-04-28
          • 2018-12-27
          • 2022-01-14
          • 2012-01-17
          • 2023-03-30
          相关资源
          最近更新 更多