온라인/오프라인 이벤트 크로스 브라우저를 탐지하는 방법은 무엇입니까?
저는 HTML5 온라인 및 오프라인 이벤트를 사용하여 브라우저가 오프라인으로 전환되는 시기를 정확하게 감지하려고 합니다.
내 코드는 다음과 같습니다.
<script>
// FIREFOX
$(window).bind("online", applicationBackOnline);
$(window).bind("offline", applicationOffline);
//IE
window.onload = function() {
document.body.ononline = IeConnectionEvent;
document.body.onoffline = IeConnectionEvent;
}
</script>
파이어폭스나 IE에서 "오프라인 작업"을 누르면 잘 작동하지만 실제로 전선을 뽑으면 무작위로 작동합니다.
이러한 변화를 감지하는 가장 좋은 방법은 무엇입니까?시간 초과로 아약스 통화를 반복하는 것을 피하고 싶습니다.
2011년 현재, 다양한 브라우저 공급업체들은 오프라인을 정의하는 방법에 대해 합의할 수 없습니다.일부 브라우저에는 오프라인 작업 기능이 있으며, 이 기능은 인터넷 액세스와 다른 네트워크 액세스와는 별개의 것으로 간주됩니다.모든 것이 엉망진창입니다.일부 브라우저 공급업체는 실제 네트워크 액세스가 손실될 때 navigator.onLine 플래그를 업데이트하고 다른 공급업체는 그렇지 않습니다.
사양에서:
사용자 에이전트가 확실히 오프라인(네트워크 연결 끊김)인 경우 false를 반환합니다.사용자 에이전트가 온라인 상태일 경우 true를 반환합니다.
이 특성의 값이 변경되면 온라인 및 오프라인 이벤트가 실행됩니다.
navigator.onLine 특성은 사용자가 링크를 추적하거나 스크립트가 원격 페이지를 요청할 때 사용자 에이전트가 네트워크에 연결하지 않을 경우 false를 반환해야 하며 그렇지 않으면 true를 반환해야 합니다.
마지막으로 사양은 다음과 같습니다.
이 속성은 본질적으로 신뢰할 수 없습니다.컴퓨터는 인터넷 액세스 없이 네트워크에 연결될 수 있습니다.
주요 브라우저 공급업체들은 "오프라인"이 무엇을 의미하는지에 대해 서로 다릅니다.
Chrome, Safari 및 Firefox(버전 41 이후)는 사용자가 "오프라인"으로 이동할 때 자동으로 감지합니다. 즉, 네트워크 케이블을 분리하면 "온라인" 이벤트 및 속성이 자동으로 실행됩니다.
Mozilla Firefox(41 버전 이전), Opera 및 IE는 다른 접근 방식을 사용하며, 작동 중인 네트워크 연결이 없는 경우에도 브라우저에서 "오프라인 모드"를 명시적으로 선택하지 않는 한 사용자를 "온라인"으로 간주합니다.
Firefox/Mozilla 동작에 대한 유효한 인수가 있으며, 이는 이 버그 보고서의 주석에 요약되어 있습니다.
https://bugzilla.mozilla.org/show_bug.cgi?id=654579
그러나 질문에 답하려면 실제로 네트워크 연결이 있는지 탐지하기 위해 온라인/오프라인 이벤트/속성에 의존할 수 없습니다.
대신 다른 방법을 사용해야 합니다.
이 Mozilla Developer 문서의 "Notes" 섹션에서는 두 가지 대체 방법에 대한 링크를 제공합니다.
https://developer.mozilla.org/en/Online_and_offline_events
"API가 브라우저에 구현되지 않은 경우 AppCache 오류 이벤트 수신 및 XMLHttpRequest의 응답을 비롯하여 다른 신호를 사용하여 오프라인 상태인지 탐지할 수 있습니다."
다음은 "AppCache 오류 이벤트 수신" 접근 방식의 예로 연결됩니다.
http://www.html5rocks.com/en/mobile/workingoffthegrid/ #toc-appcache
...그리고 "XMLHttpRequest 실패에 대한 수신 대기" 접근 방식의 예:
http://www.html5rocks.com/en/mobile/workingoffthegrid/ #toc-xml-session-request
HTH, -- 채드
오늘날 이 작업을 수행하는 오픈 소스 자바스크립트 라이브러리가 있습니다.
사용자에게 온라인/오프라인 표시를 자동으로 표시합니다.
https://github.com/HubSpot/offline
전체 README를 확인하십시오. 이 README에는 연결할 수 있는 이벤트가 포함되어 있습니다.
여기 테스트 페이지가 있습니다.아름답습니다/피드백 UI가 좋네요! :)
Offline.js Simulate UI는 오프라인.js 플러그인으로 실제 연결을 비활성화하기 위해 브루트 포스 방법을 사용할 필요 없이 페이지가 서로 다른 연결 상태에 어떻게 반응하는지 테스트할 수 있습니다.
현재 모든 주요 브라우저에서 작동하는 가장 좋은 방법은 다음 스크립트입니다.
(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
최부터근.navigator.onLine
는 모든 주요 브라우저에서 동일하게 표시되므로 사용할 수 있습니다.
if (navigator.onLine) {
// do things that need connection
} else {
// do things that don't need connection
}
올바른 방법으로 이를 지원하는 가장 오래된 버전은 다음과 같습니다.Firefox 41, IE 9, Chrome 14 및 Safari 5.
현재 이것은 거의 모든 사용자의 스펙트럼을 나타내지만, 페이지의 사용자가 어떤 기능을 가지고 있는지 항상 확인해야 합니다.
41 41만 표시되었습니다.false
사용자가 수동으로 브라우저를 오프라인 모드로 설정한 경우.은 IE 8에 .body
에 window
.
출처: caniuse
@Junto가 말했듯이 속성과 관련 이벤트는 현재 특정 웹 브라우저(특히 Firefox 데스크톱)에서 신뢰할 수 없기 때문에 주기적으로 네트워크 연결 상태를 확인하고 해당 및 이벤트를 올리는 기능(jQuery 사용)을 조금 작성했습니다.
// 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');
}
});
네비게이터.온라인이 엉망입니다.
서버에 Ajax 호출을 시도할 때 이 문제가 발생합니다.
클라이언트가 오프라인 상태일 때 다음과 같은 몇 가지 상황이 발생할 수 있습니다.
- 아약스 호출 시간이 초과되면 오류가 발생합니다.
- Ajax 호출이 성공을 반환하지만 메시지가 null입니다.
- 브라우저가 그렇게 결정하기 때문에 Ajax 호출이 실행되지 않습니다(이것은 navigator.onLine이 잠시 후에 false가 될 때일 수 있습니다).
제가 사용하고 있는 해결책은 자바스크립트로 직접 상태를 제어하는 것입니다.성공적인 통화 조건을 설정했습니다. 다른 경우에는 클라이언트가 오프라인 상태라고 가정합니다.이와 같은 것:
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);
}
});
}
HTML5에서는 다음을 사용할 수 있습니다.navigator.onLine
소유물.여기를 보십시오.
http://www.w3.org/TR/offline-webapps/ # 관련
Javascript가 "브라우저" 변수만 준비하고 오프라인 및 온라인 상태인지 알 수 있지만 실제로 네트워크 연결을 확인하지 않기 때문에 현재 동작은 무작위일 수 있습니다.
이것이 당신이 찾고 있는 것인지 알려주십시오.
안부의 말,
오프라인으로 작성한 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를 사용하는 코드 샘플이 포함되어 있습니다.
아래와 같이 오프라인 교차 검색 방법을 쉽게 탐지할 수 있습니다.
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; }
});
yoururl.com 을 다음으로 대체할 수 있습니다.document.location.pathname
.
솔루션의 핵심은 연결할 수 없는 경우 오프라인 상태에서 도메인 이름에 연결해 보는 것입니다.브라우저 간에 작동합니다.
HTML5 캐시 매니페스트의 FALLBACK 옵션을 사용하여 다음을 통해 HTML5 앱이 온라인인지 오프라인인지 확인합니다.
FALLBACK:
/online.txt /offline.txt
HTML 페이지에서 나는 온라인/오프라인 txt 파일의 내용을 읽기 위해 Javascript를 사용합니다.
<script>$.get( "urlto/online.txt", function( data ) {
$( ".result" ).html( data );
alert( data );
});</script>
오프라인일 때 스크립트는 오프라인 내용을 읽습니다.txt. 웹 페이지가 오프라인 상태인지 탐지할 수 있는 파일의 텍스트를 기준으로 합니다.
문서 본문 사용:
<body ononline="onlineConditions()" onoffline="offlineConditions()">(...)</body>
Javascript 이벤트 사용:
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 );
});
참조:
문서 본문: 온라인 이벤트
Javascript-Event : 온오프라인 이벤트
추가적인 생각:
위의 방법에서 "네트워크 연결이 인터넷 연결과 동일하지 않음" 문제를 해결하려면:애플리케이션 시작 시 Ajax로 인터넷 연결을 한 번 확인하고 온라인/오프라인 모드를 구성할 수 있습니다.사용자가 온라인 상태로 전환할 수 있도록 다시 연결 단추를 만듭니다.그리고 실패한 각 Ajax 요청에 사용자를 오프라인 모드로 다시 시작하는 기능을 추가합니다.
여기 제 해결책이 있습니다.
IE, Opera, Chrome, FireFox, Safari, IOS 8의 Phonegap WebApp 및 Android 4.4.2의 Phonegap WebApp으로 테스트됨
이 솔루션은 로컬 호스트의 FireFox에서 작동하지 않습니다.
=================================================================================
onlineCheck.js(파일 경로: "root/js/onlineCheck.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.dll(파일 경로: "root/index.dll"):
<!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(파일 경로: "root")를 확인합니다.
<?php echo 'true'; ?>
음, 당신은 브라우저 연결을 실시간으로 모니터링하고 인터넷이나 브라우저 연결이 중단되었는지 사용자에게 알릴 수 있는 자바스크립트 플러그인을 사용해 볼 수 있습니다.
와이어몽키 자바스크립트 플러그인과 데모는 여기에서 찾을 수 있습니다.
<html>
<head>
<script>
window.addEventListener("online",function(){
document.getElementById('note').
innerHTML='you are online';
});
window.addEventListener("offline",function(){
document.getElementById('note').
innerHTML='you are offline';
});
</script>
</head>
<body>
<div id="note"> </div>
</body>
</html>
언급URL : https://stackoverflow.com/questions/3181080/how-to-detect-online-offline-event-cross-browser
'programing' 카테고리의 다른 글
함수 호출에 여러 별표를 사용하면 무슨 소용이 있습니까? (0) | 2023.08.29 |
---|---|
SQL SELECT 문이 DELETE에 대해 작동하지 않습니다. (0) | 2023.08.29 |
CSS - 선택한 라디오 버튼 레이블을 스타일화하는 방법? (0) | 2023.08.29 |
mariadb의 자동 타임스탬프에 대해 너무 멍청함 (0) | 2023.08.29 |
일반 CLR 스레드에 비해 IIS 스레드가 왜 그렇게 소중합니까? (0) | 2023.08.24 |