1

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);
      })
    );
   }
  }); 
Basj
  • 41,386
  • 99
  • 383
  • 673
Sunil
  • 52
  • 9

1 Answers1

0

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.

Rupesh
  • 840
  • 1
  • 12
  • 26
  • I tried your code I have some problem first window obj is not accessible in service worker file.So I think I show write this code in my js file where I have register service worker. but next problem is "beforeinstallprompt" event fire every time when page load on desktop also and the second problem is how to get button reference of "Add to home screen banner". button is undefined.. Please help.. – Sunil Dec 26 '18 at 06:37
  • Yes , you have to add where you have registered the service worker and you can get button reference using document.queryselector() and for beforeinstall check your code. – Rupesh Dec 26 '18 at 13:52
  • Thanks Rupesh. But I had face one issue On moble two add to home screen button shows one which i have shown on beforeinstallprompt and another automatically shows by manifest file but let me know where I am wrong. – Sunil Jan 04 '19 at 18:32
  • Inspect the button using chrome dev tools and see from where and why that is coming and then remove that extra button . – Rupesh Jan 05 '19 at 04:00
  • This is button is coming due to manifest file pwa manifest file automatic show add to home screen button mobile but while i debug mobile device from crome then no add to home screen is not commit in crome so i am unable to find this button reference – Sunil Jan 05 '19 at 06:04