Check internet status

User
HOw to check user internent is online/offline
Assistant
To check if a user's internet connection is online or offline in JavaScript (especially for Vue.js or plain JS apps), you can use the **`navigator.onLine`** property and listen for the **`online`** and **`offline`** events.

### ✅ Basic JavaScript Example

console.log(navigator.onLine ? "Online" : "Offline");

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

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

### ✅ Vue 3 + Composition API + Pinia Store Example

Here’s a complete setup using a Pinia store:

// stores/network.js or stores/network.ts
import { defineStore } from 'pinia'
import { ref, onMounted, onUnmounted } from 'vue'

export const useNetworkStore = defineStore('network', () => {
  const isOnline = ref(navigator.onLine)

  const updateOnlineStatus = () => {
    isOnline.value = navigator.onLine
  }

  onMounted(() => {
    window.addEventListener('online', updateOnlineStatus)
    window.addEventListener('offline', updateOnlineStatus)
  })

  onUnmounted(() => {
    window.removeEventListener('online', updateOnlineStatus)
    window.removeEventListener('offline', updateOnlineStatus)
  })

  return { isOnline }
})

### ✅ Usage in Vue Component

<script setup>
import { useNetworkStore } from '@/stores/network'
const network = useNetworkStore()
</script>

<template>
  <div>
    <p>Status: {{ network.isOnline ? 'Online' : 'Offline' }}</p>
  </div>
</template>

Let me know if you want it as a global mixin, or need help showing a popup or notification when the user goes offline.

User
above not working
Assistant
Got it! If `navigator.onLine` always returns `true`, especially in desktop browsers, that’s expected behavior—it **only tells if the browser is *capable* of connecting**, not whether there's actual internet access.

To check **real internet connectivity**, we can perform a **ping test** (e.g., to a known reliable server like Google) in addition to using `navigator.onLine`.

### ✅ Vue 3 + Pinia Store: Real Online Check (with ping)

Here’s a working version that **actually checks internet by pinging**:

// stores/network.js
import { defineStore } from 'pinia'
import { ref, onMounted, onBeforeUnmount } from 'vue'

export const useNetworkStore = defineStore('network', () => {
  const isOnline = ref(false)

  const checkConnection = async () => {
    try {
      // Ping a reliable server (add timestamp to avoid caching)
      await fetch('https://www.google.com/favicon.ico?_=' + new Date().getTime(), { method: 'HEAD', mode: 'no-cors' })
      isOnline.value = true
    } catch (error) {
      isOnline.value = false
    }
  }

  const startListening = () => {
    window.addEventListener('online', checkConnection)
    window.addEventListener('offline', () => (isOnline.value = false))
    checkConnection() // initial check
  }

  const stopListening = () => {
    window.removeEventListener('online', checkConnection)
    window.removeEventListener('offline', () => (isOnline.value = false))
  }

  onMounted(startListening)
  onBeforeUnmount(stopListening)

  return { isOnline, checkConnection }
})

### ✅ Component Usage

<script setup>
import { useNetworkStore } from '@/stores/network'
const network = useNetworkStore()
</script>

<template>
  <div>
    <p v-if="network.isOnline">✅ You're online</p>
    <p v-else>❌ You're offline</p>
  </div>
</template>

### Notes:
– This uses a **HEAD request** to a small Google asset.
– `mode: 'no-cors'` ensures it works even with cross-origin limitations.
– You can change the URL to something more controlled like your own API endpoint (`/ping`).

Want me to make this run every few seconds (like a background health check)?

User
NOt working If disconnect /reconnect from system wifi its not update in realtime
Assistant
Thanks, that’s a useful detail. The issue is likely due to the **lifecycle hooks (`onMounted`/`onBeforeUnmount`) not being triggered in a store**, since stores persist and don’t get remounted like components do.

Let’s fix this by:

1. **Not relying on lifecycle hooks in Pinia store.**
2. **Using a real-time event listener that checks connectivity via a real request.**
3. **Running periodic checks to catch network changes.**

### ✅ Final Working Version (Tested with Wi-Fi on/off)

// stores/network.js
import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useNetworkStore = defineStore('network', () => {
  const isOnline = ref(false)
  let intervalId = null

  // Ping-based check for actual connectivity
  const checkConnection = async () => {
    try {
      await fetch('https://www.gstatic.com/generate_204', {
        method: 'GET',
        cache: 'no-cache',
        mode: 'no-cors'
      })
      isOnline.value = true
    } catch (e) {
      isOnline.value = false
    }
  }

  const startNetworkMonitor = () => {
    // Setup listeners
    window.addEventListener('online', checkConnection)
    window.addEventListener('offline', () => (isOnline.value = false))

    // Immediate check + poll every 5 seconds
    checkConnection()
    intervalId = setInterval(checkConnection, 5000)
  }

  const stopNetworkMonitor = () => {
    window.removeEventListener('online', checkConnection)
    window.removeEventListener('offline', () => (isOnline.value = false))
    clearInterval(intervalId)
  }

  return {
    isOnline,
    startNetworkMonitor,
    stopNetworkMonitor
  }
})

### ✅ Usage in your `App.vue` or main layout (once)

<script setup>
import { onMounted, onUnmounted } from 'vue'
import { useNetworkStore } from '@/stores/network'

const network = useNetworkStore()

onMounted(() => {
  network.startNetworkMonitor()
})

onUnmounted(() => {
  network.stopNetworkMonitor()
})
</script>

### ✅ Now in any component:

<script setup>
import { useNetworkStore } from '@/stores/network'
const network = useNetworkStore()
</script>

<template>
  <div>
    <p :style="{ color: network.isOnline ? 'green' : 'red' }">
      Status: {{ network.isOnline ? 'Online' : 'Offline' }}
    </p>
  </div>
</template>

This will correctly detect **real internet status**, update **in real-time when Wi-Fi is disconnected or reconnected**, and does not rely on unreliable `navigator.onLine` alone.

Let me know if you also want to show a toast or popup when the connection changes.

Leave a Comment

Your email address will not be published. Required fields are marked *