nived
nived

Reputation: 141

How to check if Offline with service worker?

I've been following this tutorial https://codelabs.developers.google.com/codelabs/offline/#7

So far I was able to make my service worker cache the offline page and load it but I want to show this offline.html page only when there is no internet access. And the way it works now is it shows it every time I refresh the page even with internet access unless I check the Bypass for network checkbox in Chrome's Application tab in the developer tools.

self.addEventListener('fetch', function(event) {
    console.log(event.request.url);
    event.respondWith(
        fetch('https://mysite/offline.html')
    );;
});

Upvotes: 3

Views: 8347

Answers (2)

Abk
Abk

Reputation: 2233

You can make use of the navigator.onLine. It returns true for online and false otherwise.

window.addEventListener('DOMContentLoaded', function() {
  var status = document.getElementById("status");

  function updateOnlineStatus(event) {
    var condition = navigator.onLine ? "online" : "offline";

    status.className = condition;
    status.innerHTML = condition.toUpperCase();
  }
  window.addEventListener('online',  updateOnlineStatus);
  window.addEventListener('offline', updateOnlineStatus);
});
#status {
  width: 100%;
  font: bold 1em sans-serif;
  color: #FFF;
  padding: 0.5em;
}

.online {
  background: green;
}

.offline {
  background: red;
}
<div id="status" class="online"> ONLINE </div>
<p> Toggle your network connection to see the effect </p>

Read more on MDN

Upvotes: 7

ravi
ravi

Reputation: 1145

you can use navigator.onLine which will return true or false according to the network connectivity, you can take a look at it Best practices for detecting offline state in a service worker might help.

Upvotes: 3

Related Questions