Создание web-приложения для работы без подключения к сети

Основная идея — проверять перед сохранением данных значение navigator.onLine и слушать события online (для сохранения на сервере), offline (для сохранения в localStorage) и load (для загрузки несохранённых данных на сервер при загрузке страницы после подключения к сети).

Пример:

// save the string
function saveStatusLocally(txt) {
  window.localStorage.setItem("status", txt);
}
 
// read the string
function readStatus() {
   return window.localStorage.getItem("status");
}
function whatIsYourCurrentStatus() {
  var status = window.prompt("What is your current status?");
  if (!status) return;
  if (navigator.onLine) {
    sendToServer(status);
  } else {
    saveStatusLocally(status);
  }
}
 
function sendLocalStatus() {
  var status = readStatus();
  if (status) {
    sendToServer(status);
    window.localStorage.removeItem("status");
  }
}
 
 
window.addEventListener("load", function() {
   if (navigator.onLine) {
     sendLocalStatus();
   }
}, true);
 
window.addEventListener("online", function() {
  sendLocalStatus();
}, true);
 
window.addEventListener("offline", function() {
  alert("You're now offline. If you update your status, it will be sent when you go back online");
}, true);

Оригинал — http://hacks.mozilla.org/2010/01/offline-web-applications/

LEAVE A COMMENT