복붙노트

[JQUERY] 어떻게 온라인 / 오프라인 이벤트 크로스 브라우저를 감지?

JQUERY

어떻게 온라인 / 오프라인 이벤트 크로스 브라우저를 감지?

해결법


  1. 1.현재 2011 년, 다양한 브라우저 벤더는 오프라인을 정의하는 방법에 동의하지 않을 수 있습니다. 일부 브라우저는 다시 인터넷에 다른 네트워크 액세스의 부족에 별도 생각해 보자 오프라인으로 작업 기능을 가지고있다. 모든 것은 엉망이다. 실제 네트워크 액세스가 손실 된 경우 일부 브라우저 벤더가 navigator.onLine 플래그를 업데이트, 다른 사람은하지 않습니다.

    현재 2011 년, 다양한 브라우저 벤더는 오프라인을 정의하는 방법에 동의하지 않을 수 있습니다. 일부 브라우저는 다시 인터넷에 다른 네트워크 액세스의 부족에 별도 생각해 보자 오프라인으로 작업 기능을 가지고있다. 모든 것은 엉망이다. 실제 네트워크 액세스가 손실 된 경우 일부 브라우저 벤더가 navigator.onLine 플래그를 업데이트, 다른 사람은하지 않습니다.

    사양에서 :

    마지막으로, 사양 노트 :


  2. 2.주요 브라우저 벤더는 무엇을 "오프라인"방법에 차이가있다.

    주요 브라우저 벤더는 무엇을 "오프라인"방법에 차이가있다.

    크롬, 사파리, 파이어 폭스는 자동으로 "오프라인"갈 때 감지 (버전 41부터) - 당신이 당신의 네트워크 케이블을 분리 할 때 "온라인"이벤트와 속성이 자동으로 실행됩니다 것을 의미한다.

    명시 적으로 브라우저에서 "오프라인 모드"를 선택하지 않는 한 모질라 파이어 폭스 (버전 41 이전), 오페라, 그리고 IE는 다른 접근 방식을 가지고 가고, "온라인"을 고려 - 당신이 작동하는 네트워크 연결이없는 경우에도 마찬가지입니다.

    이 버그 보고서의 주석에 설명되어 파이어 폭스 / 모질라의 행동에 대한 유효한 인수가 있습니다 :

    https://bugzilla.mozilla.org/show_bug.cgi?id=654579

    하지만, 질문에 대답하는 - 당신은 실제로 네트워크 연결이있는 경우 감지하는 온라인 / 오프라인 이벤트 / 부동산에 의존 할 수 없다.

    대신, 당신은 대체 방법을 사용해야합니다.

    이 모질라 개발자 문서의 "주의 사항"섹션이 다른 방법에 대한 링크를 제공합니다 :

    https://developer.mozilla.org/en/Online_and_offline_events

    "API가 브라우저에 구현되어 있지 않은 경우, 당신은 당신이 오프라인 XMLHttpRequest의에서 AppCache를 오류 이벤트 및 응답을 듣기를 포함하는 경우 감지하는 다른 신호를 사용할 수 있습니다"

    은 "AppCache를 오류 이벤트를 수신"접근의 예이 링크 :

    http://www.html5rocks.com/en/mobile/workingoffthegrid/#toc-appcache

    ... 그리고 "XMLHttpRequest의 실패에 대한 듣고"접근 방식의 예 :

    http://www.html5rocks.com/en/mobile/workingoffthegrid/#toc-xml-http-request

    HTH, - 차드


  3. 3.오늘이 일을 오픈 소스 자바 스크립트 라이브러리가있다 : 그것은 Offline.js라고.

    오늘이 일을 오픈 소스 자바 스크립트 라이브러리가있다 : 그것은 Offline.js라고.

    https://github.com/HubSpot/offline

    전체 README를 확인하십시오. 그것은 당신이에 연결할 수 이벤트가 포함되어 있습니다.

    다음은 테스트 페이지입니다. 그것은 아름답다 / 그런데 멋진 피드백 UI를 가지고! :)


  4. 4.모든 주요 브라우저에 지금 작동하는 가장 좋은 방법은 다음과 같은 스크립트입니다 :

    모든 주요 브라우저에 지금 작동하는 가장 좋은 방법은 다음과 같은 스크립트입니다 :

    (function () {
        var displayOnlineStatus = document.getElementById("online-status"),
            isOnline = function () {
                displayOnlineStatus.innerHTML = "Online";
                displayOnlineStatus.className = "online";
            },
            isOffline = function () {
                displayOnlineStatus.innerHTML = "Offline";
                displayOnlineStatus.className = "offline";
            };
    
        if (window.addEventListener) {
            /*
                Works well in Firefox and Opera with the 
                Work Offline option in the File menu.
                Pulling the ethernet cable doesn't seem to trigger it.
                Later Google Chrome and Safari seem to trigger it well
            */
            window.addEventListener("online", isOnline, false);
            window.addEventListener("offline", isOffline, false);
        }
        else {
            /*
                Works in IE with the Work Offline option in the 
                File menu and pulling the ethernet cable
            */
            document.body.ononline = isOnline;
            document.body.onoffline = isOffline;
        }
    })();
    

    출처 : http://robertnyman.com/html5/offline/online-offline-events.html


  5. 5.최근 때문에, navigator.onLine는 모든 주요 브라우저에서 동일한 표시, 따라서 가능한 것입니다.

    최근 때문에, navigator.onLine는 모든 주요 브라우저에서 동일한 표시, 따라서 가능한 것입니다.

    if (navigator.onLine) {
      // do things that need connection
    } else {
      // do things that don't need connection
    }
    

    올바른 방법으로이를 지원하는 가장 오래된 버전은 다음과 같습니다 파이어 폭스 (41), IE 9, 크롬 14, 사파리 5.

    현재이 사용자의 거의 전체 스펙트럼을 대표 할 것입니다,하지만 당신은 항상 페이지의 사용자가 기능이 무엇인지 확인해야합니다.

    사용자가 오프라인 모드에서 수동으로 브라우저를 넣으면 FF (41)에 이전, 그것은 단지 거짓 보여줄 것입니다. IE 8에서는,이 건물은 대신 윈도우의 몸에 있었다.

    출처 : caniuse


  6. 6.나는 정기적으로 검사 네트워크 연결 상태가 적절한 오프라인을 올릴 것으로 (jQuery를 사용) 약간의 기능을 썼다 있도록 window.navigator.onLine 속성과 관련된 이벤트는, @Junto 말했듯이 특정 웹 브라우저 (특히 파이어 폭스 바탕 화면)에 현재 신뢰할 온라인 이벤트 :

    나는 정기적으로 검사 네트워크 연결 상태가 적절한 오프라인을 올릴 것으로 (jQuery를 사용) 약간의 기능을 썼다 있도록 window.navigator.onLine 속성과 관련된 이벤트는, @Junto 말했듯이 특정 웹 브라우저 (특히 파이어 폭스 바탕 화면)에 현재 신뢰할 온라인 이벤트 :

    // Global variable somewhere in your app to replicate the 
    // window.navigator.onLine variable (this last is not modifiable). It prevents
    // the offline and online events to be triggered if the network
    // connectivity is not changed
    var IS_ONLINE = true;
    
    function checkNetwork() {
      $.ajax({
        // Empty file in the root of your public vhost
        url: '/networkcheck.txt',
        // We don't need to fetch the content (I think this can lower
        // the server's resources needed to send the HTTP response a bit)
        type: 'HEAD',
        cache: false, // Needed for HEAD HTTP requests
        timeout: 2000, // 2 seconds
        success: function() {
          if (!IS_ONLINE) { // If we were offline
            IS_ONLINE = true; // We are now online
            $(window).trigger('online'); // Raise the online event
          }
        },
        error: function(jqXHR) {
          if (jqXHR.status == 0 && IS_ONLINE) {
            // We were online and there is no more network connection
            IS_ONLINE = false; // We are now offline
            $(window).trigger('offline'); // Raise the offline event
          } else if (jqXHR.status != 0 && !IS_ONLINE) {
            // All other errors (404, 500, etc) means that the server responded,
            // which means that there are network connectivity
            IS_ONLINE = true; // We are now online
            $(window).trigger('online'); // Raise the online event
          }
        }
      });
    }
    

    이처럼 사용할 수 있습니다 :

    // Hack to use the checkNetwork() function only on Firefox 
    // (http://stackoverflow.com/questions/5698810/detect-firefox-browser-with-jquery/9238538#9238538)
    // (But it may be too restrictive regarding other browser
    // who does not properly support online / offline events)
    if (!(window.mozInnerScreenX == null)) {
        window.setInterval(checkNetwork, 30000); // Check the network every 30 seconds
    }
    

    (jQuery를의 도움으로) 오프라인 및 온라인 이벤트를 수신하려면 :

    $(window).bind('online offline', function(e) {
      if (!IS_ONLINE || !window.navigator.onLine) {
        alert('We have a situation here');
      } else {
        alert('Battlestation connected');
      }
    });
    

  7. 7.navigator.onLine는 엉망

    navigator.onLine는 엉망

    서버에 아약스 전화를 할 때 나는이 직면하고 있습니다.

    클라이언트가 오프라인 상태 일 때 몇 가지 경우가 있습니다 :

    내가 사용하고이 솔루션은 자바 스크립트와 상태 나 자신을 제어하는 ​​것입니다. 나는 다른 어떤 경우에 나는 클라이언트가 오프라인 가정, 호출이 성공의 조건을 설정합니다. 이 같은:

    var offline;
    pendingItems.push(item);//add another item for processing
    updatePendingInterval = setInterval("tryUpdatePending()",30000);
    tryUpdatePending();
    
        function tryUpdatePending() {
    
            offline = setTimeout("$('#offline').show()", 10000);
            $.ajax({ data: JSON.stringify({ items: pendingItems }), url: "WebMethods.aspx/UpdatePendingItems", type: "POST", dataType: "json", contentType: "application/json; charset=utf-8",
              success: function (msg) {
                if ((!msg) || msg.d != "ok")
                  return;
                pending = new Array(); //empty the pending array
                $('#offline').hide();
                clearTimeout(offline);
                clearInterval(updatePendingInterval);
              }
            });
          }
    

  8. 8.HTML5에서 당신은 navigator.onLine 속성을 사용할 수 있습니다. 이봐:

    HTML5에서 당신은 navigator.onLine 속성을 사용할 수 있습니다. 이봐:

    http://www.w3.org/TR/offline-webapps/#related

    자바 스크립트 만 "브라우저"변수를 준비로 아마 현재의 행동은 랜덤하고 온라인 경우있는 거 오프라인을 알고 있지만, 실제로는 네트워크 연결을 확인하지 않습니다.

    이것이 당신이 찾고있는 경우 알려주세요.

    친절 감사,


  9. 9.내가 오프라인을 위해 쓴 것을 require.js 모듈을 찾아주세요.

    내가 오프라인을 위해 쓴 것을 require.js 모듈을 찾아주세요.

    define(['offline'], function (Offline) {
        //Tested with Chrome and IE11 Latest Versions as of 20140412
        //Offline.js - http://github.hubspot.com/offline/ 
        //Offline.js is a library to automatically alert your users 
        //when they've lost internet connectivity, like Gmail.
        //It captures AJAX requests which were made while the connection 
        //was down, and remakes them when it's back up, so your app 
        //reacts perfectly.
    
        //It has a number of beautiful themes and requires no configuration.
        //Object that will be exposed to the outside world. (Revealing Module Pattern)
    
        var OfflineDetector = {};
    
        //Flag indicating current network status.
        var isOffline = false;
    
        //Configuration Options for Offline.js
        Offline.options = {
            checks: {
                xhr: {
                    //By default Offline.js queries favicon.ico.
                    //Change this to hit a service that simply returns a 204.
                    url: 'favicon.ico'
                }
            },
    
            checkOnLoad: true,
            interceptRequests: true,
            reconnect: true,
            requests: true,
            game: false
        };
    
        //Offline.js raises the 'up' event when it is able to reach
        //the server indicating that connection is up.
        Offline.on('up', function () {
            isOffline = false;
        });
    
        //Offline.js raises the 'down' event when it is unable to reach
        //the server indicating that connection is down.
        Offline.on('down', function () {
            isOffline = true;
        });
    
        //Expose Offline.js instance for outside world!
        OfflineDetector.Offline = Offline;
    
        //OfflineDetector.isOffline() method returns the current status.
        OfflineDetector.isOffline = function () {
            return isOffline;
        };
    
        //start() method contains functionality to repeatedly
        //invoke check() method of Offline.js.
        //This repeated call helps in detecting the status.
        OfflineDetector.start = function () {
            var checkOfflineStatus = function () {
                Offline.check();
            };
            setInterval(checkOfflineStatus, 3000);
        };
    
        //Start OfflineDetector
        OfflineDetector.start();
        return OfflineDetector;
    });
    

    이 블로그 게시물을 읽고 내가 당신의 생각을 알려 주시기 바랍니다. http://zen-and-art-of-programming.blogspot.com/2014/04/html-5-offline-application-development.html 그것은 클라이언트가 오프라인 상태 일 때 감지하는 offline.js를 사용하여 코드 샘플이 포함되어 있습니다.


  10. 10.아래처럼 쉽게 크로스 브라우저 방식을 오프라인으로 감지 할 수 있습니다

    아래처럼 쉽게 크로스 브라우저 방식을 오프라인으로 감지 할 수 있습니다

    var randomValue = Math.floor((1 + Math.random()) * 0x10000)
    
    $.ajax({
          type: "HEAD",
          url: "http://yoururl.com?rand=" + randomValue,
          contentType: "application/json",
          error: function(response) { return response.status == 0; },
          success: function() { return true; }
       });
    

    당신은 document.location.pathname에 의해 yoururl.com을 대체 할 수 있습니다.

    이 솔루션의 핵심은, 당신이 연결할 수없는 경우, 도메인 이름에 연결을 시도한다 - 당신이 오프라인 상태입니다. 크로스 브라우저를 작동합니다.


  11. 11.내 HTML5 응용 프로그램이 온라인 또는 오프라인 있는지 확인하는 HTML5 캐시 매니페스트에서 대체 옵션을 사용합니다 :

    내 HTML5 응용 프로그램이 온라인 또는 오프라인 있는지 확인하는 HTML5 캐시 매니페스트에서 대체 옵션을 사용합니다 :

    FALLBACK:
    /online.txt /offline.txt
    

    HTML 페이지에서 내가 온라인 / 오프라인 TXT 파일의 내용을 읽을 자바 스크립트 사용 :

    <script>$.get( "urlto/online.txt", function( data ) {
    $( ".result" ).html( data );
    alert( data );
    });</script>
    

    때 오프라인 스크립트는 offline.text의 내용을 읽습니다. 웹 페이지가 온라인 오프라인의 경우 파일의 텍스트를 기반으로 당신은 감지 할 수 있습니다.


  12. 12.여기 내 솔루션입니다.

    여기 내 솔루션입니다.

    안드로이드 4.4.2에 폰갭 웹 애플리케이션 IOS (8)과 같은 폰갭 웹 애플리케이션과 같은 IE, 오페라, 크롬, 파이어 폭스, 사파리, 테스트

    이 솔루션은 로컬 호스트에서 파이어 폭스와 함께 작동하지 않습니다.

    =================================================================================

    온라인 Check.js (파일 경로 : "루트 / JS / 온라인 Check.js) :

    var isApp = false;
    
    function onLoad() {
            document.addEventListener("deviceready", onDeviceReady, false);
    }
    
    function onDeviceReady() {
        isApp = true;
        }
    
    
    function isOnlineTest() {
        alert(checkOnline());
    }
    
    function isBrowserOnline(no,yes){
        //Didnt work local
        //Need "firefox.php" in root dictionary
        var xhr = XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHttp');
        xhr.onload = function(){
            if(yes instanceof Function){
                yes();
            }
        }
        xhr.onerror = function(){
            if(no instanceof Function){
                no();
            }
        }
        xhr.open("GET","checkOnline.php",true);
        xhr.send();
    }
    
    function checkOnline(){
    
        if(isApp)
        {
            var xhr = new XMLHttpRequest();
            var file = "http://dexheimer.cc/apps/kartei/neu/dot.png";
    
            try {
                xhr.open('HEAD', file , false); 
                xhr.send(null);
    
                if (xhr.status >= 200 && xhr.status < 304) {
                    return true;
                } else {
                    return false;
                }
            } catch (e) 
            {
                return false;
            }
        }else
        {
            var tmpIsOnline = false;
    
            tmpIsOnline = navigator.onLine;
    
            if(tmpIsOnline || tmpIsOnline == "undefined")
            {
                try{
                    //Didnt work local
                    //Need "firefox.php" in root dictionary
                    var xhr = XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHttp');
                    xhr.onload = function(){
                        tmpIsOnline = true;
                    }
                    xhr.onerror = function(){
                        tmpIsOnline = false;
                    }
                    xhr.open("GET","checkOnline.php",false);
                    xhr.send();
                }catch (e){
                    tmpIsOnline = false;
                }
            }
            return tmpIsOnline;
    
        }
    }
    

    =================================================================================

    index.html을 (파일 경로 : "루트 / index.html을") :

    <!DOCTYPE html>
    <html>
    
    
    <head>
        ...
    
        <script type="text/javascript" src="js/onlineCheck.js" ></script>
    
        ...
    
    </head>
    
    ...
    
    <body onload="onLoad()">
    
    ...
    
        <div onclick="isOnlineTest()">  
            Online?
        </div>
    ...
    </body>
    
    </html>
    

    =================================================================================

    ( "루트"파일 경로를) Online.php 확인 :

    <?php echo 'true'; ?> 
    

  13. 13.글쎄, 당신은 인터넷 또는 인터넷과 브라우저 연결이 내려 가면 실시간으로 통지 사용자의 브라우저 연결을 모니터링 할 수 있습니다 자바 스크립트 플러그인을 시도 할 수 있습니다.

    글쎄, 당신은 인터넷 또는 인터넷과 브라우저 연결이 내려 가면 실시간으로 통지 사용자의 브라우저 연결을 모니터링 할 수 있습니다 자바 스크립트 플러그인을 시도 할 수 있습니다.

    Wiremonkey 자바 스크립트 플러그인 그리고 데모는 여기에서 찾을 수 있습니다


  14. 14.문서 바디를 사용 :

    문서 바디를 사용 :

    <body ononline="onlineConditions()" onoffline="offlineConditions()">(...)</body>
    

    자바 스크립트 이벤트를 사용 :

    window.addEventListener('load', function() {
    
      function updateOnlineStatus() {
    
        var condition = navigator.onLine ? "online" : "offline";
        if( condition == 'online' ){
            console.log( 'condition: online')
        }else{
            console.log( 'condition: offline')
        }
    
      }
    
      window.addEventListener('online',  updateOnlineStatus );
      window.addEventListener('offline', updateOnlineStatus );
    
    });
    

    참고: 문서 바디 : ononline 이벤트 자바 스크립트 이벤트 : 온라인 및 오프라인 이벤트

    추가 생각 : 주위에 제공하기 위해 위의 방법에서 문제의 "네트워크 연결하면 인터넷 연결과 동일하지 않습니다": 당신은 응용 프로그램 시작에 아약스에 한 번 인터넷 연결을 확인하거나 온라인 / 오프라인 모드를 구성 할 수 있습니다. 사용자가 온라인에 대한 재 연결 만들기 버튼을 클릭합니다. 그리고 각 실패 아약스 요청에 오프라인 모드로 사용자가 다시 걷어 기능을 추가 할 수 있습니다.

  15. from https://stackoverflow.com/questions/3181080/how-to-detect-online-offline-event-cross-browser by cc-by-sa and MIT license