Testing the online/offline status of the Internet connection with JavaScript

Published on 2020-07-12 • Modified on 2020-07-12

In this snippet, we will see how to detect the status of the Internet connection with JavaScript. A message is displayed just above the snippet's code. To test if it works, with Firefox, you can enable the "Work offline" option of the "File" menu, you can deactivate your Wifi or unplug your network cable. The message changes as soon as it detects a change of the status. Be careful that the implementation may be different from one browser to another; read the documentation for all the details (link below).

 * I am using a JavaScript module to isolate the code of each snippet.
 * In fact it's a Vue.js mixin. Take the code called by the mounted()
 * or the snippetXX() function.
export default {
  data: {
    isOnline: null
  methods: {
    snippet101 () {
      const self = this
      window.addEventListener('offline', function (e) { self.snippet101() })
      window.addEventListener('online', function (e) { self.snippet101() })
    updateOnlineStatus () {
      this.isOnline = navigator.onLine
  mounted () {
    if (this.isArticle(101)) {
HTML demo of the snippet

≪ isOnline ? trans.status_online : trans.status_offline ≫

 More on Stackoverflow   Read the doc  More on the web  Random snippet

  Work with me!