Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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')
    );;
});
like image 370
nived Avatar asked Dec 18 '25 23:12

nived


1 Answers

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

like image 63
Abk Avatar answered Dec 20 '25 14:12

Abk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!