我已经创建了服务工作程序文件和清单文件,并在我的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);
})
);
}
});
答案 0 :(得分:0)
添加以下代码以检查默认的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;
}
希望这会有所帮助。