A simple utility you can use to know if you are online or not.
It relies on cross-fetch, thus it aims to work on Node, React Native and Web (with browserify / webpack) environments.
At the command-line terminal:
npm install --save isomorphic-is-online
Then in your code:
// Using ES6 modules with Babel or TypeScript
import isOnline from "isomorphic-is-online";
// Using CommonJS modules
const isOnline = require("isomorphic-is-online").default;
import isOnline from "isomorphic-is-online";
console.log("Are you able to reach the internet?");
isOnline().then(isOnline => {
console.log("Response:", isOnline);
});
isOnline
returns a promise which resolves to true
if a connection can be established and resolves to false
if it cannot or the network requests time out.
An optional object can be passed to isOnline
to customize some options:
option | type | default | description |
---|---|---|---|
urls | array of strings | ["//1.1.1.1"] | List of urls to request to check connection status |
timeout | number | 3000 | Milliseconds to wait before timing out the request |
const options = {
urls: ["https://www.apple.com", "//1.1.1.1"],
timeout: 5000
};
isOnline(options).then(isOnline => {
if (isOnline) {
hackTheInternet();
} else {
beQuiet();
}
});