티스토리 뷰



안녕하세요. 우봉이 입니다.


오늘은 웹에서 온/오프라인을 체크하는 자바스크립트 라이브러리인 Offline.js 를 알아보도록 하겠습니다.


간단하게, 연결 상태만 체크하는 것이면 ajax로 간단하게 해결할 수는 있지만, 그래도 예쁜 디자인과 기능을 위해 사용해보았습니다. ㅎㅎ


http://github.hubspot.com/offline/docs/welcome/


위에 링크로 접속해서 간단한 API 사용법과 파일을 다운로드 받습니다.


다은로드 받으면 문서도있고, 테마도 있고, js 파일도 있고 다 있습니다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<head>
<script src="../offline.min.js"></script>
 
<!--
Themes:
<link rel="stylesheet" href="./themes/offline-theme-default.css" />
<link rel="stylesheet" href="./themes/offline-theme-default-indicator.css" />
<link rel="stylesheet" href="./themes/offline-theme-slide.css" />
<link rel="stylesheet" href="./themes/offline-theme-slide-indicator.css" />
<link rel="stylesheet" href="./themes/offline-theme-chrome.css" />
<link rel="stylesheet" href="./themes/offline-theme-chrome-indicator.css" />
<link rel="stylesheet" href="./themes/offline-theme-hubspot.css" />
-->
 
<link rel="stylesheet" href="../themes/offline-theme-default.css" />
<link rel="stylesheet" href="../themes/offline-language-english.css" />
 
<script>
var run = function(){
  var req = new XMLHttpRequest();
  req.timeout = 5000;
  req.open('GET''http://localhost:8888/walter/0'true);
  req.send();
}
 
setInterval(run, 3000);
</script>
</head>
<body>
</body>
 
 
cs


위 소스가 이제 다운로드 받은 파일 내부에 test폴더에 index.html로 있는 파일 소스코드 내용인데

가장 기본적인 사용방법입니다.


라이브러리와 원하는 테마를 추가하고, 아래 처럼 주기적인 ajax 요청을 날리면,  요청 결과에 따라 확인해서 인터넷이 온/오프라인인지 체크해주는 것 같습니다. ㅎㅎ


요청은 이런식으로 주기적인 시간을 주고 체크하는 방법이 있고, 아니면 라이브러리 옵션과 메소드를 활용해서 원하는 이벤트 때에 사용하는 방법이 있습니다.


바로바로, Offline.check() 를 사용하는 것입니다.


Offline.check() 메소드는 현재 인터넷 상태를 확인하여 저장하는 것으로, 메소드 실행 후

alert 또는 console.log 에 Offline.state 를 확인해보시면, up(온) 또는 down(오프라인) 으로 결과가 나옵니다.


또한 저처럼 기본사용법에 run으로 주기적으로 확인하지 않으시고,


Offline.options = {checks: {xhr: {url: '/connection-test'}}};

Offline.options = {checks: {image: {url: 'my-image.gif'}, active: 'image'}}


위 처럼 요청 Url을 설정하여 Offline.check() 시에 확인할 url도 세팅할 수 있습니다.

Default check 옵션으로 해당 사이트의 favicon.ico 를 확인하니, 없는 경우에는 주의하셔야 할 것 같습니다 ^^


또한, Offline.js 는 다양한 이벤트를 지원도 해서, 버튼을 비활성화 시키거나, alert창을 띄우거나 등 다양하게 활용하실 수 있습니다.


이벤트의 종류는 기본적으로 


Offline.on(event, handler, context): Bind an event. 


Events:

  • up: The connection has gone from down to up
  • down: The connection has gone from up to down
  • confirmed-up: A connection test has succeeded, fired even if the connection was already up
  • confirmed-down: A connection test has failed, fired even if the connection was already down
  • checking: We are testing the connection
  • reconnect:started: We are beginning the reconnect process
  • reconnect:stopped: We are done attempting to reconnect
  • reconnect:tick: Fired every second during a reconnect attempt, when a check is not happening
  • reconnect:connecting: We are reconnecting now
  • reconnect:failure: A reconnect check attempt failed
  • requests:flush: Any pending requests have been remade
  • requests:hold: A new request is being held


Offline.off(event, handler): Unbind an event


다음과 같네요.


저의 경우 버튼 비활성화를 위해 사용해봤는데요

클래스명에 monitored 라고 버튼에 주고, 

1
2
3
4
5
6
7
8
9
10
  Offline.on("down"function() {
    $('.monitored').attr('disabled''disabled');
    alert("인터넷 연결이 끊어졌습니다.");
  });
  
  Offline.on("up"function() {
    $('.monitored').removeAttr('disabled''disabled');
    alert("인터넷 연결이 되었습니다.");
  });
 
cs


이렇게 사용도 하고 있고,


자바스크립트 메소드 생성해서 사용할 때 상단에 아래와 같이

1
2
3
4
5
6
    Offline.check();
 
    if ( Offline.state == 'down') {
      alert("인터넷 연결이 끊겼습니다. 연결 후 사용 가능합니다.");
      return;
    }
cs

작성하시면, 해당 자바스크립트 메소드 실행 시간에, 온/오프라인을 체크해서 실행 여부를 결정할 수 도 있습니다.


더욱 자세하게 알고 싶으신 분은, github 공유 파일을 풀로 받으셔서, 공유 문서와 함께 예제와 테마를 각각 실행해보세요.


다음 이미지는 기본으로 제공하는 크롬 테마의 온/오프라인 화면입니다.




저는 대충 언어팩중에 한글 팩은 없어서, 영어로 되어있는 영어팩 번역해서 대충 사용했습니다. ㅎㅎ


혹시 필요하실 분이 있을까는 잘 모르겠지만 ㅎㅎ 파일첨부해드릴게요~!


offline-language-ko.css



댓글