motorscript.com

Enabling Persisted Storage for your web app on Chrome

Published:
According to Google Developer Docs, Chrome grants persistent storage permissions if any of these are satisfied:
  • The site is bookmarked (and the user has 5 or less bookmarks)
  • The site has high site engagement
  • The site has been added to home screen
  • The site has push notifications enabled
We will use the last two options to get the permission.
  1. Adding our app to home screen.

    • To enable adding our site to homescreen, first add a manifest file - manifest.json to the root.
      {
          "short_name": "OCR GT",
          "name": "OCR GT",
          "icons": [
            {
              "src": "favicon.png",
              "type": "image/png",
              "sizes": "64x64"
            },
            {
              "src": "awecode-512.png",
              "type": "image/png",
              "sizes": "512x512"
            }
          ],
          "start_url": "/",
          "background_color": "#3367D6",
          "display": "standalone",
          "scope": "/",
          "theme_color": "#3367D6"
      }
        
      Change the values as per your requirement. Link the manifest file from your index.html. Add the following within the head tag.
      <link rel="manifest" href="manifest.json">
    • Add a service worker with the file sw.js (following sample from Google Chrome's Github)
      const PRECACHE = 'precache-v1';
      const RUNTIME = 'runtime';
      
      const PRECACHE_URLS = [
        'index.html',
        './', // Alias for index.html
      ];
      
      self.addEventListener('install', event => {
        event.waitUntil(
          caches.open(PRECACHE)
            .then(cache => cache.addAll(PRECACHE_URLS))
            .then(self.skipWaiting())
        );
      });
      
      self.addEventListener('activate', event => {
        const currentCaches = [PRECACHE, RUNTIME];
        event.waitUntil(
          caches.keys().then(cacheNames => {
            return cacheNames.filter(cacheName => !currentCaches.includes(cacheName));
          }).then(cachesToDelete => {
            return Promise.all(cachesToDelete.map(cacheToDelete => {
              return caches.delete(cacheToDelete);
            }));
          }).then(() => self.clients.claim())
        );
      });
      
      self.addEventListener('fetch', event => {
        // Skip cross-origin requests, like those for Google Analytics.
        if (event.request.url.startsWith(self.location.origin)) {
          event.respondWith(
            caches.match(event.request).then(cachedResponse => {
              if (cachedResponse) {
                return cachedResponse;
              }
      
              return caches.open(RUNTIME).then(cache => {
                return fetch(event.request).then(response => {
                  // Put a copy of the response in the runtime cache.
                  return cache.put(event.request, response.clone()).then(() => {
                    return response;
                  });
                });
              });
            })
          );
        }
      });
                                  
      Register the service worker from your app:
      if ('serviceWorker' in navigator) {
        navigator.serviceWorker.register('sw.js');
      }
    • Now, open your app in Chrome, open Dev Tools -> Application tab -> Manifest, click on Add to homescreen. DevTools Add to Homescreen
      Image Courtesy: Google
  2. Enable push notifications

    • Click on the info icon or the Secure lock icon before the URL in the address bar. Then click on the Site Settings. Chrome Site Settings
    • And allow push notifications.
      Chrome Allow Push Notifications
  3. Ask Chrome for the persisted storage permissions.

    if (navigator.storage && navigator.storage.persist)
      navigator.storage.persist().then(granted => {
        if (granted)
          console.log("Storage will not be cleared except by explicit user action");
        else
          console.log("Storage may be cleared by the UA under storage pressure.");
      });
Now, your web app should print "Storage will not be cleared except by explicit user action" on the console.