7
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

JavaScriptでネットワークのオンライン・オフライン監視する関数を作った

Last updated at Posted at 2019-06-11

JSで端末のネットワークを監視して、オフラインの時はアラートを出す実装をしてた際のメモです。

ネットワークの監視は以下のように書いても良いんですが、

window.addEventListener('offline', () => {
    console.log('offline');
})

window.addEventListener('online', () => {
    console.log('online');
})

もうちょっとわかりやすく出来ればと思って、以下のように関数化してみました。

const watchOnline = function(callback) {
    window.addEventListener('online', () => callback(true))
    window.addEventListener('offline', () => callback(false))
    callback(navigator.onLine)
}

watchOnline((online) => {
    if (online) {
        console.log('online')
    } else {
        console.log('offline')
    }
})

これだと、ページ表示の際に実行されるのも良いです。

サンプルです。

See the Pen watch online/offline by daichi (@kandai) on CodePen.

参考
https://developer.mozilla.org/ja/docs/Web/API/NavigatorOnLine/onLine

7
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?