簡體   English   中英

無法跟蹤PWA添加到主屏幕事件

[英]Unable to track pwa add to home screen events

我已經創建了一個服務工作者文件和清單文件,並在我的index.html文件中注冊了服務工作者文件。 我想跟蹤有多少用戶可以看到“添加到主屏幕按鈕”,以及有多少用戶單擊了“添加到主屏幕”。 我的申請符合pwa的所有標准。 我已在服務文件中使用“ beforeinstallprompt”事件,但在顯示“添加到主屏幕”時未觸發。

我的服務人員代碼如下。

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);
      })
    );
   }
  }); 

添加以下代碼以檢查默認的Windows提示符,然后阻止該默認提示符並在需要時觸發該事件。

 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; } 

希望這可以幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM