बैकग्राउंड में डेटा को समय-समय पर कैसे सिंक करें

Cecilia Cong
Cecilia Cong

मॉडर्न तरीका

समय-समय पर होने वाले बैकग्राउंड सिंक की मदद से, प्रोग्रेसिव वेब ऐप्लिकेशन या सर्विस वर्कर की मदद से लोड होने वाले पेज को लॉन्च करने पर, नया कॉन्टेंट दिखाया जा सकता है. ऐसा तब होता है, जब ऐप्लिकेशन या पेज का इस्तेमाल नहीं किया जा रहा होता है. इस दौरान, बैकग्राउंड में डेटा डाउनलोड होता रहता है.

Periodic Background Sync API का इस्तेमाल करना

सर्विस वर्कर इंस्टॉल होने के बाद, Permissions API का इस्तेमाल करके periodic-background-sync के बारे में क्वेरी करें. ऐसा किसी विंडो या सर्विस वर्कर के कॉन्टेक्स्ट से किया जा सकता है.

const status = await navigator.permissions.query({
  name: 'periodic-background-sync',
});
if (status.state === 'granted') {
  // Periodic background sync can be used.
} else {
  // Periodic background sync cannot be used.
}

समय-समय पर होने वाले सिंक को रजिस्टर करने के लिए, टैग और कम से कम सिंक्रनाइज़ेशन इंटरवल (minInterval) दोनों की ज़रूरत होती है. टैग, रजिस्टर किए गए सिंक की पहचान करता है, ताकि एक से ज़्यादा सिंक रजिस्टर किए जा सकें. यहां दिए गए उदाहरण में, टैग का नाम 'content-sync' है और minInterval एक दिन है.

navigator.serviceWorker.ready.then(async registration => {
  try {
    await registration.periodicSync.register('get-cats', { minInterval: 24 * 60 * 60 * 1000 });
    console.log('Periodic background sync registered.');
  } catch (err) {
    console.error(err.name, err.message);
  }
});

रजिस्ट्रेशन टैग की कलेक्शन पाने के लिए, periodicSync.getTags() को कॉल करें. यहां दिए गए उदाहरण में, टैग के नामों का इस्तेमाल करके यह पुष्टि की जाती है कि कैश मेमोरी को अपडेट करने की प्रोसेस चालू है, ताकि उसे दोबारा अपडेट न करना पड़े.

const registration = await navigator.serviceWorker.ready;
if ('periodicSync' in registration) {
  const tags = await registration.periodicSync.getTags();
  // Only update content if sync isn't set up.
  if (!tags.includes('content-sync')) {
    updateContentOnPageLoad();
  }
} else {
  // If periodic background sync isn't supported, always update.
  updateContentOnPageLoad();
}

समय-समय पर होने वाले बैकग्राउंड सिंक इवेंट का जवाब देने के लिए, अपने सर्विस वर्कर में periodicsync इवेंट हैंडलर जोड़ें. इसे पास किए गए इवेंट ऑब्जेक्ट में, रजिस्ट्रेशन के दौरान इस्तेमाल की गई वैल्यू से मेल खाने वाला टैग पैरामीटर शामिल होगा. उदाहरण के लिए, अगर समय-समय पर होने वाले बैकग्राउंड सिंक को नाम 'content-sync' से रजिस्टर किया गया है, तो event.tag 'content-sync' होगा.

self.addEventListener('periodicsync', (event) => {
  if (event.tag === 'content-sync') {
    event.waitUntil(syncContent());
  }
});

वेबसाइट का अलग-अलग ब्राउज़र पर चलना

Browser Support

  • Chrome: 80.
  • Edge: 80.
  • Firefox: not supported.
  • Safari: not supported.

Source

क्लासिक तरीका

क्लासिक तरीके में, बैकग्राउंड में डेटा अपडेट करने के बजाय, लोड होने पर डेटा अपडेट किया जाता है. इससे उपयोगकर्ता के ऐप्लिकेशन लोड करने पर, डेटा तुरंत उपलब्ध हो जाता है.

इस बारे में और पढ़ें

डेमो

HTML

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <link
      rel="icon"
      href=""
    />
    <link rel="manifest" href="./manifest.json" />
    <title>How to periodically synchronize data in the background</title>
    <link rel="stylesheet" href="/style.css" />
    <!-- TODO: Devsite - Removed inline handlers -->
    <!-- <script src="/script.js" defer></script> -->
  </head>
  <body>
    <h1>How to periodically synchronize data in the background</h1>
    <p class="available">Periodic background sync can be used. Install the app first.</p>
    <p class="not-available">Periodic background sync cannot be used.</p>
    <h2>Last updated</h2>
    <p class="last-updated">Never</p>
    <h2>Registered tags</h2>
    <ul>
      <li>None yet.</li>
    </ul>
  </body>
</html>

CSS


        html {
  box-sizing: border-box;
  font-family: system-ui, sans-serif;
  color-scheme: dark light;
}

*,
*:before,
*:after {
  box-sizing: inherit;
}

body {
  margin: 1rem;
}
        

JS


        const available = document.querySelector('.available');
const notAvailable = document.querySelector('.not-available');
const ul = document.querySelector('ul');
const lastUpdated = document.querySelector('.last-updated');

const updateContent = async () => {
  const data = await fetch(
    'https://worldtimeapi.org/api/timezone/Europe/London.json'
  ).then((response) => response.json());
  return new Date(data.unixtime * 1000);
};

const registerPeriodicBackgroundSync = async (registration) => {
  const status = await navigator.permissions.query({
    name: 'periodic-background-sync',
  });
  if (status.state === 'granted' && 'periodicSync' in registration) {
    try {
      // Register the periodic background sync.
      await registration.periodicSync.register('content-sync', {
        // An interval of one day.
        minInterval: 24 * 60 * 60 * 1000,
      });
      available.hidden = false;
      notAvailable.hidden = true;

      // List registered periodic background sync tags.
      const tags = await registration.periodicSync.getTags();
      if (tags.length) {
        ul.innerHTML = '';
      }
      tags.forEach((tag) => {
        const li = document.createElement('li');
        li.textContent = tag;
        ul.append(li);
      });

      // Update the user interface with the last periodic background sync data.
      const backgroundSyncCache = await caches.open('periodic-background-sync');
      if (backgroundSyncCache) {
        const backgroundSyncResponse =
          backgroundSyncCache.match('/last-updated');
        if (backgroundSyncResponse) {
          lastUpdated.textContent = `${await fetch('/last-updated').then(
            (response) => response.text()
          )} (periodic background-sync)`;
        }
      }

      // Listen for incoming periodic background sync messages.
      navigator.serviceWorker.addEventListener('message', async (event) => {
        if (event.data.tag === 'content-sync') {
          lastUpdated.textContent = `${await updateContent()} (periodic background sync)`;
        }
      });
    } catch (err) {
      console.error(err.name, err.message);
      available.hidden = true;
      notAvailable.hidden = false;
      lastUpdated.textContent = 'Never';
    }
  } else {
    available.hidden = true;
    notAvailable.hidden = false;
    lastUpdated.textContent = `${await updateContent()} (manual)`;
  }
};

if ('serviceWorker' in navigator) {
  window.addEventListener('load', async () => {
    const registration = await navigator.serviceWorker.register('./sw.js');
    console.log('Service worker registered for scope', registration.scope);

    await registerPeriodicBackgroundSync(registration);
  });
}