the Chromium logo

The Chromium Projects

Detecting online status in polymer

How to check for online status in Polymer

IMPORTANT: Online status does not necessarily indicate that the user can access the internet. See Comments/Discussion for more information.

Problem

In a Polymer website or application, I want to detect whether the user's device is online or offline. I want to use this value as a JavaScript variable.

Solution

Use navigator.onLine!

  1. Create a declared property in your custom element that will store the online status boolean value.

    static get properties() {
      return {
        isOnline_: {type: Boolean},
      };
    }
    
  2. In your element's constructor, set the initial value of your declared property to navigator.onLine.

    constructor() {
      super();
    
      /** @type {boolean} */
      this.isOnline_ = navigator.onLine;
    }
    
  3. In your element's ready callback, add event listeners for the online and offline events. The callbacks on these event listeners should update the state of your declared property.

    /** @override */
    ready() {
      super.ready();
    
      window.addEventListener('online', () => {
        this.isOnline_ = true;
      });
    
      window.addEventListener('offline', () => {
        this.isOnline_ = false;
      });
    }
    
  4. You can now use your bound property (isOnline_ in this example) in your element's code!

    ...
    if (this.isOnline_) {
      showOnlineMessage();
    } else {
      showOfflineMessage();
    }
    ...
    

Example CL

References

Comment/Discussion

Navigator.onLine is somewhat limited in functionality. This quote from MDN's Navigator.onLine article has more details:

In Chrome and Safari, if the browser is not able to connect to a local area network (LAN) or a router, it is offline; all other conditions return true. So while you can assume that the browser is offline when it returns a false value, you cannot assume that a true value necessarily means that the browser can access the internet. You could be getting false positives, such as in cases where the computer is running a virtualization software that has virtual ethernet adapters that are always "connected." Therefore, if you really want to determine the online status of the browser, you should develop additional means for checking.

While there doesn't seem to be a standardized way to detect internet connection status from a WebUI, here are some leads to get started: