JQuery Mobile Detected if there's internet Con

2020-02-26 08:21发布

What is the best way to detect if there's internet connection or not on my mobile via my web app?

5条回答
我只想做你的唯一
2楼-- · 2020-02-26 08:42

in simple JS code this can done, causation all featured devices not have JS supported however for web-based application this is very minimum code to use

online = window.navigator.onLine;
if (navigator.onLine) {
  alert('you are online');
} else {
  alert('you are offline');
}
查看更多
Explosion°爆炸
3楼-- · 2020-02-26 08:49

if you want to check every X seconds the connection.

        $(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
        });
查看更多
Animai°情兽
4楼-- · 2020-02-26 08:53

There's no code necessary for this -- it's part of the HTML5 API. Check the value of window.navigator.onLine -- it will be false if the user is offline.

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

查看更多
够拽才男人
5楼-- · 2020-02-26 08:56

An option might be changing the Ajax settings to add a specific timeout, then add an error handler that looks for a textStatus (second argument) of 'timeout'.

When a timeout occurs, either internet connectivity is spotty or your site is down.


Using ajaxSetup to set option defaults for all requests:

$.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");
    }
});
查看更多
Deceive 欺骗
6楼-- · 2020-02-26 08:58

If you want something with more compatibility, reliability and customisability than window.navigator.onLine, try my jQuery plugin: http://tomriley.net/blog/archives/111

查看更多
登录 后发表回答