Network Information API

Экспериментальная возможность: Это экспериментальная технология
Так как спецификация этой технологии ещё не стабилизировалась, смотрите таблицу совместимости по поводу использования в различных браузерах. Также заметьте, что синтаксис и поведение экспериментальной технологии может измениться в будущих версиях браузеров, вслед за изменениями спецификации.

API Network Information позволяет определить тип интернет-подключения системы ('wifi', 'cellular' и т.д.). Эту информацию можно использовать, к примеру, для того, чтобы предоставлять контент большего либо меньшего разрешения в зависимости от качества соединения. Весь API состоит из интерфейса NetworkInformation, добавленного в глобальный объект Navigator как свойство Navigator.connection.

Примечание: Эта возможность доступна в Web Workers.

Примеры

Определение изменения соединения

Данный пример отслеживает изменение подключения пользователя.

js
var connection =
  navigator.connection || navigator.mozConnection || navigator.webkitConnection;
var type = connection.effectiveType;

function updateConnectionStatus() {
  console.log(
    "Connection type changed from " + type + " to " + connection.effectiveType,
  );
  type = connection.effectiveType;
}

connection.addEventListener("change", updateConnectionStatus);

Предварительная загрузка крупных ресурсов

The connection object is useful for deciding whether to preload resources that take large amounts of bandwidth or memory. This example would be called soon after page load to check for a connection type where preloading a video may not be desirable. If a cellular connection is found, then the preloadVideo flag is set to false. For simplicity and clarity, this example only tests for one connection type. A real-world use case would likely use a switch statement or some other method to check all of the possible values of NetworkInformation.type. Regardless of the type value you can get an estimate of connection speed through the NetworkInformation.effectiveType property.

js
let preloadVideo = true;
var connection =
  navigator.connection || navigator.mozConnection || navigator.webkitConnection;
if (connection) {
  if (connection.effectiveType === "slow-2g") {
    preloadVideo = false;
  }
}

Интерфейсы

NetworkInformation

Даёт возможность получить информацию о сетевом соединении, а также возможность получать события при изменении типа соединения. Невозможно создавать экземпляры данного интерфейса, для получения доступа используйте Navigator.

Спецификации

Specification
Network Information API

Совместимость с браузерами

api.NetworkInformation

Report problems with this compatibility data on GitHub
desktopmobile
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
NetworkInformation
change event
downlink
downlinkMax
Experimental
effectiveType
rtt
saveData
type
Experimental
typechange event
DeprecatedNon-standard
Available in workers

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support
No support
No support
Experimental. Expect behavior to change in the future.
Non-standard. Check cross-browser support before using.
Deprecated. Not for use in new websites.
See implementation notes.

api.Navigator.connection

Report problems with this compatibility data on GitHub
desktopmobileserver
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
Deno
Node.js
connection

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support
No support
No support
See implementation notes.

Смотрите также