إنشاء صفحة احتياطية بلا اتصال بالإنترنت

تاريخ النشر: 24 أيلول (سبتمبر) 2020

ما هو الشيء المشترك بين تطبيق "مساعد Google" وتطبيق Slack وتطبيق Zoom وأي تطبيق آخر خاص بمنصة معيّنة على هاتفك أو جهاز الكمبيوتر؟ صحيح، فهم يقدّمون لك شيئًا دائمًا على الأقل. حتى عندما لا يكون لديك اتصال بالشبكة، سيظل بإمكانك فتح تطبيق "مساعد Google" أو إدخال Slack أو تشغيل Zoom. قد لا تحصل على أي شيء مفيد بشكل خاص أو حتى لا تتمكّن من تحقيق ما أردت تحقيقه، ولكن على الأقل ستحصل على شيء وسيكون التطبيق تحت السيطرة.

تطبيق "مساعد Google" للأجهزة الجوّالة بلا اتصال بالإنترنت
مساعد Google

تطبيق Slack للأجهزة الجوّالة بلا إنترنت
‫Slack

تكبير تطبيق الأجهزة الجوّالة بلا اتصال بالإنترنت
تكبير/تصغير

باستخدام التطبيقات الخاصة بمنصات معيّنة، لن تحصل على أي شيء حتى في حال عدم توفّر اتصال بالشبكة.

في المقابل، لا يمكنك عادةً الوصول إلى أي محتوى على الويب عندما تكون غير متصل بالإنترنت. يوفّر لك Chrome لعبة الديناصورات بلا إنترنت، وهذا كل ما في الأمر.

تطبيق Google Chrome للأجهزة الجوّالة يعرض لعبة الديناصور التي يمكن لعبها بلا إنترنت
‫Google Chrome على أجهزة iOS

تطبيق Google Chrome على الكمبيوتر يعرض لعبة الديناصور التي يمكن تشغيلها بلا إنترنت.
‫Google Chrome لنظام التشغيل macOS

على الويب، عندما لا يكون لديك اتصال بالشبكة، لن تحصل على أي شيء بشكل تلقائي.

صفحة احتياطية بلا إنترنت مع مشغّل خدمات مخصّص

مع ذلك، ليس من الضروري أن يكون الأمر كذلك. بفضل برامج الخدمة وواجهة برمجة التطبيقات Cache Storage API، يمكنك توفير تجربة مخصّصة بلا إنترنت للمستخدمين. يمكن أن تكون هذه الصفحة بسيطة تحمل علامتك التجارية وتتضمّن المعلومات التي تفيد بأنّ المستخدم غير متصل بالإنترنت حاليًا، ولكن يمكن أن تكون أيضًا حلاً أكثر إبداعًا، مثل لعبة متاهة trivago الشهيرة التي لا تتطلّب الاتصال بالإنترنت مع زر إعادة الاتصال اليدوي وعداد تنازلي لمحاولة إعادة الاتصال تلقائيًا.

صفحة trivago المتوفّرة بلا إنترنت مع متاهة trivago المتوفّرة بلا إنترنت
متاهة trivago بلا إنترنت

تسجيل مشغّل الخدمات

ويمكن تحقيق ذلك من خلال عامل خدمة. يمكنك تسجيل عامل خدمة من صفحتك الرئيسية كما في نموذج الرمز البرمجي أدناه. ويتم ذلك عادةً مرة واحدة بعد تحميل تطبيقك.

window.addEventListener("load", () => {
  if ("serviceWorker" in navigator) {
    navigator.serviceWorker.register("service-worker.js");
  }
});

رمز مشغّل الخدمات

قد تبدو محتويات ملف عامل الخدمة الفعلي معقّدة بعض الشيء للوهلة الأولى، ولكن من المفترض أن توضّح التعليقات في المثال أدناه الأمور. الفكرة الأساسية هي التخزين المؤقت المُسبَق لملف باسم offline.html لا يتم عرضه إلا عند تعذُّر طلبات التنقّل، والسماح للمتصفّح بالتعامل مع جميع الحالات الأخرى:

/*
Copyright 2015, 2019, 2020, 2021 Google LLC. All Rights Reserved.
 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at
 http://www.apache.org/licenses/LICENSE-2.0
 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
*/

// Incrementing OFFLINE_VERSION will kick off the install event and force
// previously cached resources to be updated from the network.
// This variable is intentionally declared and unused.
// Add a comment for your linter if you want:
// eslint-disable-next-line no-unused-vars
const OFFLINE_VERSION = 1;
const CACHE_NAME = "offline";
// Customize this with a different URL if needed.
const OFFLINE_URL = "offline.html";

self.addEventListener("install", (event) => {
  event.waitUntil(
    (async () => {
      const cache = await caches.open(CACHE_NAME);
      // Setting {cache: 'reload'} in the new request ensures that the
      // response isn't fulfilled from the HTTP cache; i.e., it will be
      // from the network.
      await cache.add(new Request(OFFLINE_URL, { cache: "reload" }));
    })()
  );
  // Force the waiting service worker to become the active service worker.
  self.skipWaiting();
});

self.addEventListener("activate", (event) => {
  event.waitUntil(
    (async () => {
      // Enable navigation preload if it's supported.
      // See https://developers.google.com/web/updates/2017/02/navigation-preload
      if ("navigationPreload" in self.registration) {
        await self.registration.navigationPreload.enable();
      }
    })()
  );

  // Tell the active service worker to take control of the page immediately.
  self.clients.claim();
});

self.addEventListener("fetch", (event) => {
  // Only call event.respondWith() if this is a navigation request
  // for an HTML page.
  if (event.request.mode === "navigate") {
    event.respondWith(
      (async () => {
        try {
          // First, try to use the navigation preload response if it's
          // supported.
          const preloadResponse = await event.preloadResponse;
          if (preloadResponse) {
            return preloadResponse;
          }

          // Always try the network first.
          const networkResponse = await fetch(event.request);
          return networkResponse;
        } catch (error) {
          // catch is only triggered if an exception is thrown, which is
          // likely due to a network error.
          // If fetch() returns a valid HTTP response with a response code in
          // the 4xx or 5xx range, the catch() will NOT be called.
          console.log("Fetch failed; returning offline page instead.", error);

          const cache = await caches.open(CACHE_NAME);
          const cachedResponse = await cache.match(OFFLINE_URL);
          return cachedResponse;
        }
      })()
    );
  }

  // If our if() condition is false, then this fetch handler won't
  // intercept the request. If there are any other fetch handlers
  // registered, they will get a chance to call event.respondWith().
  // If no fetch handlers call event.respondWith(), the request
  // will be handled by the browser as if there were no service
  // worker involvement.
});

صفحة الاحتياط المتوفّرة بلا إنترنت

ملف offline.html هو المكان الذي يمكنك فيه إطلاق العنان لإبداعك وتكييفه مع احتياجاتك وإضافة علامتك التجارية. يعرض المثال أدناه الحد الأدنى لما يمكن تحقيقه. يوضّح هذا المثال كيفية إعادة التحميل يدويًا استنادًا إلى الضغط على زر، بالإضافة إلى إعادة التحميل تلقائيًا استنادًا إلى حدث online والاستطلاع المنتظم للخادم.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />

    <title>You are offline</title>

    <!-- Inline the page's stylesheet. -->
    <style>
      body {
        font-family: helvetica, arial, sans-serif;
        margin: 2em;
      }

      h1 {
        font-style: italic;
        color: #373fff;
      }

      p {
        margin-block: 1rem;
      }

      button {
        display: block;
      }
    </style>
  </head>
  <body>
    <h1>You are offline</h1>

    <p>Click the button below to try reloading.</p>
    <button type="button">⤾ Reload</button>

    <!-- Inline the page's JavaScript file. -->
    <script>
      // Manual reload feature.
      document.querySelector("button").addEventListener("click", () => {
        window.location.reload();
      });

      // Listen to changes in the network state, reload when online.
      // This handles the case when the device is completely offline.
      window.addEventListener('online', () => {
        window.location.reload();
      });

      // Check if the server is responding and reload the page if it is.
      // This handles the case when the device is online, but the server
      // is offline or misbehaving.
      async function checkNetworkAndReload() {
        try {
          const response = await fetch('.');
          // Verify we get a valid response from the server
          if (response.status >= 200 && response.status < 500) {
            window.location.reload();
            return;
          }
        } catch {
          // Unable to connect to the server, ignore.
        }
        window.setTimeout(checkNetworkAndReload, 2500);
      }

      checkNetworkAndReload();
    </script>
  </body>
</html>

عرض توضيحي

يمكنك الاطّلاع على صفحة الاحتياط بلا إنترنت أثناء العمل في العرض التوضيحي المضمّن أدناه. إذا كنت مهتمًا، يمكنك استكشاف رمز المصدر على GitHub.

ملاحظة جانبية حول إتاحة تثبيت تطبيقك

بعد أن أصبح موقعك الإلكتروني يتضمّن صفحة احتياطية يمكن الوصول إليها بلا إنترنت، قد تتساءل عن الخطوات التالية. لإتاحة تثبيت تطبيقك، عليك إضافة بيان تطبيق ويب، ويمكنك اختياريًا وضع استراتيجية تثبيت.

ملاحظة جانبية حول عرض صفحة احتياطية بلا إنترنت باستخدام Workbox.js

ربما سمعت عن Workbox. ‫Workbox هي مجموعة من مكتبات JavaScript لإتاحة استخدام تطبيقات الويب بلا إنترنت. إذا كنت تفضّل كتابة تعليمات برمجية أقل خاصة ببرنامج عامل الخدمة، يمكنك استخدام وصفة Workbox لصفحة غير متصلة بالإنترنت فقط.

في ما يلي، تعرَّف على كيفية تحديد استراتيجية تثبيت لتطبيقك.