コフス技術ブログ

JavaScriptでオンライン・オフラインを検出する

JavaScriptでネットワークコンディションを検出する例です。

オンラインとオフラインの判定、加えてイベントリスナーにてオンライン復帰とオフライン化した際の処理を行います。

class checkNetworkCondition {
constructor() {
// setIntervalのid
this.countId = null
// 再チェックまでの秒数
this.recheckTimer = 5
// カウント中か否か
this.isCounting = false
window.addEventListener("online", () => {
if (!this.countId || this.isCounting) {
return
}
this.check()
clearInterval(this.countId)
})
window.addEventListener("offline", () => {
this.check()
})
this.check()
}
counting() {
let count = 0
this.isCounting = true
this.countId = setInterval(() => {
if(count < this.recheckTimer) {
console.log("再チェックまで:", this.recheckTimer - count)
}
count = count + 1
if(count === this.recheckTimer + 1) {
clearInterval(this.countId)
this.isCounting = false
this.check()
}
}, 1000)
}
check() {
const nowDate = new Date()
const isOnline = window.navigator.onLine
if(isOnline) {
console.log("😄 オンライン:", nowDate)
}
if(!isOnline) {
console.log("😱 オフライン:", nowDate)
this.counting()
}
}
}
new checkNetworkCondition()

実行するとコンソールにてオンラインとオフラインの判定が確認できます。

オフラインの場合はオンラインになるまでネットワークコンディションのチェックを、実行中にネットワークコンディションが変更された場合には再チェックが行われます。

処理前にネットワークコンディションの判定が必要な時、またユーザーへのフィードバックUIとして活用出来そうです。

参考:オンライン・オフラインイベント - MDN