Redirect via HTML5 Offline Online events

Asked

Viewed 39 times

1

How to identify if HTML5 app identifies and redirects if offline or online?

Ex: When opening the app if you are without internet loads a warning html and online redirects to a website.

I found this code but I do not know if it is possible to modify it this way.

     function updateOnlineStatus(msg) {
       var status = document.getElementById("status");
       var condition = navigator.onLine ? "ONLINE" : "OFFLINE";
       status.setAttribute("class", condition);
       var state = document.getElementById("state");
       state.innerHTML = condition;
       var log = document.getElementById("log");
       log.appendChild(document.createTextNode("Event: " + msg + "; status=" + condition + "\n"));
     }
     function loaded() {
       updateOnlineStatus("load");
       document.body.addEventListener("offline", function () {
         updateOnlineStatus("offline")
       }, false);
       document.body.addEventListener("online", function () {
         updateOnlineStatus("online")
       }, false);
     }
<!doctype html>
 <html>
 <head>
   <style>...</style>
 </head>
 <body onload="loaded()">
   <div id="status"><p id="state"></p></div>
   <div id="log"></div>
 </body>
 </html>

Reference: https://developer.mozilla.org/en-US/docs/Online_and_offline_events

1 answer

1


I resolved it this way:

   function updateOnlineStatus(evento) {
       var status = document.getElementById("status");
       var condition = navigator.onLine ? location.href='online.html' : location.href='offline.html' ;          
     }
     function loaded() {
       updateOnlineStatus("load");
       document.body.addEventListener("offline", function () {
         updateOnlineStatus("offline")
       }, false);
       document.body.addEventListener(function () {
         updateOnlineStatus("online")
       }, false);
     }
<!doctype html>
 <html>
 <head>
 
 </head>
 <body onload="loaded()">

 </body>
 </html>

If there is a simpler method I thank you for your cooperation.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.