Get type of user connection in javascript

Asked

Viewed 174 times

1

how can I get the type of user connection in javascript? I want to know if it is accessing my site via wireless, 4G, wired internet...

All this in javascript

2 answers

1

navegator.connection()

Here is a brief summary of use

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 function

console.log(navegator.connection)

is similar to this

NetworkInformationdownlink: 2.85
effectiveType: "4g"
onchange: null
rtt: 150
__proto__: NetworkInformation

1


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

The support of this API still this low and desktop (or mobile) browsers like Firefox, Safary and Edge still do not support it others partially support some of its features.

Among some of your objections you may have access to:

  • downloadlink: represents the capacity of the connection download rate
  • rtt: average return time of a request (latency)
  • effectiveType: 2g, 3g, 4, slow-2g (defined by mean rtt and downloadlink)
  • Connectiontype: bluetooth, Cellular, ethernet, Mixed, None, other, unknow, wifi, Wimax (connection type)
  • onchange: function to monitor connection changes

You can monitor changes in connection through a "Handler" or even observing the event 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 with.

inserir a descrição da imagem aqui

Link to the Specification

Browser other questions tagged

You are not signed in. Login or sign up in order to post.