How to detect "net::ERR_CONNECTION_REFUSED"

Viewed 223

i'm use Vue 2 and i wanna detect sockjs errors and show notification. (Like 'Connection lost','connection timeout' etc. ) I have no idea how to do it

enter image description here

1 Answers

The browser has a built in method called navigator.onLine, which returns either true or false. Now to watch for connection changes you can add an event listener on window,

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

You can incorporate this into a Vue component with something like:

export default {
  data() {
    return {
      online: navigator.onLine
    };
  },
  mounted() {
    window.addEventListener("online", this.onchange);
    window.addEventListener("offline", this.onchange);
    this.onchange();
  },
  beforeDestroy() {
    window.removeEventListener("online", this.onchange);
    window.removeEventListener("offline", this.onchange);
  },
  methods: {
    onchange() {
      this.online = navigator.onLine;
      this.$emit(this.online ? "online" : "offline");
    }
  }
};

And then use v-if="!online" to selectively render you're offline banner.


Alternatively, take a look at: v-offline, it instead works by pinging an endpoint, which has the advantage of being able to detect when the user is online but with very poor internet connection (loading), however is an overall less efficient approach.

import offline from 'v-offline';

export default {
  components: {
    offline
  },

  methods: {
    handleConnectivityChange(status) {
      console.log(status);
    }
  }
}

For most sock.js methods, you can get this information from the Event parameter returned by the callback. But for detecting network connection, and other common tasks, it's usually more robust to do natively, as outlined above.

Related