Network Information API: The Web API I didn’t know I needed

Network Information API: The Web API I didn’t know I needed

·

2 min read

Like most junior developers I’ve never really cared about the type of network connection application users are on, because we are too busy trying to figure out how to center a div element.

However recently while working on a PWA and making use of the background syncs I came across an instance where I was requesting large sets of data from the server, now this is probably no issue if the user is on wifi or a stable ethernet connection, but on a cellular or mobile connection, it may be quite an expensive considering the cost of prepaid mobile connectivity.

The solution was to therefore find out what type of connection the user is on before making calls for large data sets, and if the connection happens to be on cellular, make the user aware and they can decide on whether to proceed with the synchronization or wait until on a wifi connection.

Demonstration | Example

The network information API can be accessed via the connection property of the Navigator interface;

connection-property-demonstration.png

As you can see the connection property returns network information, I was only interested in the “type” property at the time for my use case but this interface allows you to do numerous cool stuff; you can set event listeners such as onchange and ontypechange. For the sake of demonstration, I will now proceed to set the ontypechange property to a function and switch to a different connection for the event to be triggered;

ontypechange-demonstration.png

In the example above I set ontypechange to an anonymous function that logs the message “Connection Type Changed” and the connection interface. Note that the connection type changed from cellular to wifi when I switched the connection on my phone from mobile data to wifi.

Conclusion

It is worth mentioning that this API is still experimental and is expected to have some additions and or changes, and so I advise you to check browser support before you commit to making use of it in production.

Reference