CoyoteSS

Jan 9, 2021

3 min read

How to Get Information About User Network Connection in JavaScript

Web API has many interesting and useful things for different use cases, one of them is Network Information API and today I explain you how to use it and why.

Photo by Thomas Jensen on Unsplash

Introduction

Connection Type

const connectionType: string = navigator.connection.type;console.log(connectionType); // cellular
enum ConnectionType {
"cellular",
"wifi",
"wimax",
"bluetooth",
"ethernet",
"mixed",
"other",
"unknown",
"none"
};

Effective Connection Type (ECT):

const ect: string = navigator.connection.effectiveType;console.log(ect); // 4g
enum EffectiveConnectionType {
"slow-2g",
"2g",
"3g",
"4g"
};
  • slow-2g —when user has 0–50 Kbps internet speed, page loads very slow, don’t recommended to show any media content such as images, videos, audio etc.
  • 2g — when user has 50–70 Kbps internet speed, looks like slow-2g, but we can show small images.
  • 3g — normal 70–700 Kbps internet speed, user can load images, LQ videos or audio.
  • 4g — good internet speed from 700 Kbps to infinity, suited for any media content.

RTT

const rtt: number = navigator.connection.rtt; // get rtt time in millisecondsconsole.log(rtt); // 100

Downlink

const downlink: number = navigator.connection.downlink;console.log(downlink); // 2.8

How to find out about changing the Internet connection

navigator.connection.addEventListener('change', (event: Event) => {
console.log(event.currentTarget.effectiveType);
});

Browser Compatibility

Bonus for Angular developers

import { InjectionToken } from '@angular/core';export const NETWORK_INFORMATION: InjectionToken<NetworkInformation | null> = new InjectionToken('Network Information API', {
factory: () => {
if (window?.navigator?.connection) {
return window.navigator.connection;
}
},
});

Conclusion