javascriptangularjsservice-workera2hs

Unable to track pwa add to home screen events


I have create a service worker file and manifeast file and register service worker file in my index.html file. I want to track that how many users can see "Add to home screen button" and how many users have click "Add to home screen" . MY application has meet all the criteria of pwa. I have used "beforeinstallprompt" event in service file but its not fire when "Add to home screen" shows.

My service worker code are given below.

var doCache = true;
var version = 481;
// Name our cache
var CACHE_NAME = 'health-cache-v='+version;
var filesToCache = [
'index.html'
];

let deferredPrompt;

self.addEventListener('beforeinstallprompt', (event) => { 
 onsole.log('add to home screen popup show'); 
event.userChoice.then(choiceResult => {
if (choiceResult.outcome === 'accepted') {
    console.log('User accepted the add to home screen popup'); 
  } else {
    console.log('User dismissed the add to home screen popup');

  }     
});
});


// Delete old caches that are not our current one!
self.addEventListener("activate", event => {
  const cacheWhitelist = [CACHE_NAME];
event.waitUntil(
  caches.keys()
    .then(keyList =>
      Promise.all(keyList.map(key => {
      if (!cacheWhitelist.includes(key)) {
        console.log('Deleting cache: ' + key)
        return caches.delete(key);
      }
    }))
   )
  );
 });


 self.addEventListener('install', function(event) {
 if (doCache) {
   event.waitUntil(
    caches.open(CACHE_NAME)
      .then(function(cache) {       
        cache.addAll(filesToCache);         
          console.log('cached');
    })
   );
  }
 });

 self.addEventListener('fetch', function(event) { 
  if (doCache) {         
    event.respondWith(
      caches.match(event.request).then(function(response) {
          return response || fetch(event.request);
      })
    );
   }
  }); 

Solution

  • Add the below code to check for default windows prompt then prevent that default prompt and trigger that event whenever when you want.

    var deferredPrompt; // to store event
    
    // check for windows default prompt and preventing it 
    window.addEventListener('beforeinstallprompt',(event)=>{
    
      console.log('Default a2hs triggered' ,event);
      // here preventing default prompt
      event.preventDefault();
      // storing that event
      deferredPrompt = event;
      return false;
    })
    
    
    // now lets says you want to trigger it when addToHomeScreen() invokes as 
    button.addEventListener('click', addToHomeScreen());
    
    function addToHomeScreen() {
      addToHomeScreen.style.display = 'block';
      if (deferredPrompt) {
      // here prompting that event
        deferredPrompt.prompt();  // --> you missed this code
    
        deferredPrompt.userChoice.then(function(choiceResult) {
          console.log(choiceResult.outcome);
    
          if (choiceResult.outcome === 'dismissed') {
            console.log('User cancelled installation');
          } else {
            console.log('User added to home screen');
          }
        });
    
        deferredPrompt = null;
      }

    Hope this helps.