Get user connection type in javascript

1

How can I get the user's connection type in javascript? I want to know if he is accessing my site via wireless, 4G, internet wired ...

All this in javascript

    
asked by anonymous 05.04.2018 / 22:25

2 answers

1

You can use the Network Information API available in navigator.connection .

Support for this API is still low, and desktop (or mobile) browsers such as Firefox, Safary and Edge still do not support it, and some support some of its features.

Among some of your options you can access:

  • downloadlink : represents the download rate of the connection
  • rtt : average round trip time for a request (latency)
  • effectiveType : 2g, 3g, 4, slow-2g (defined by rtt and downloadlink )
  • ConnectionType : bluetooth, cellular, ethernet, mixed, none, other, unknow, wifi, wimax
  • onchange : function to monitor changes in the connection

You can monitor changes to the connection through a handler or even by watching the change :

function changeHandler(e) {
    //
}
navigator.connection.onchange = changeHandler;

navigator.connection.addEventListener('change', changeHandler);

TEST :

if ( navigator.connection ) {
    console.log(navigator.connection)
} else {
    console.log('Seu navegador não suporta a "Network Information API"')
}

Support caniuse.com

Link to Specification

    
05.04.2018 / 22:53
1
navegator.connection()

Here is a brief usage summary

if(navigator.connection) {
    if((navigator.connection.downlinkMax && navigator.connection.downlinkMax>1)
      || navigator.connection.type=='wifi') {
      document.body.classList.add('hifi');
    }
    else {
      document.body.classList.add('lofi');
    }
}

Now a return of the function

console.log(navegator.connection)

is similar to this

NetworkInformationdownlink: 2.85
effectiveType: "4g"
onchange: null
rtt: 150
__proto__: NetworkInformation
    
05.04.2018 / 22:42