Hi I've been trying to create a PWA and it works great on ANDROID but fails to function in iOS. I've got all the right functions except that later I've discovered that BeforeInstallPromptEvent is not supported in Safari... So I made sure that function is not run when on Safari.. but still it doesn't work. Is there something else that I have to do make PWA work in Safari. I think the issue is with service worker registration.
sw.js
var cacheName = 'cachecard';
var filesToCache = [
'./',
'./index.html',
'./css/style.css',
'./js/main.js'
];
/* Start the service worker and cache all of the app's content */
self.addEventListener('install', function(e) {
e.waitUntil(
caches.open(cacheName).then(function(cache) {
return cache.addAll(filesToCache);
})
);
self.skipWaiting();
});
/* Serve cached content when offline */
self.addEventListener('fetch', function(e) {
e.respondWith(
caches.match(e.request).then(function(response) {
return response || fetch(e.request);
})
);
});
index.html
<div id="installContainer" class="hidden" >
<button id="butInstall" type="button">
*INSTALL APP*
</button>
</div>
<script src="js/main.js"></script>
<script>
// Initialize deferredPrompt for use later to show browser install prompt.
let deferredPrompt;
const divInstall = document.getElementById('installContainer');
const butInstall = document.getElementById('butInstall');
if ( !(varUA.indexOf("iphone") > -1 || varUA.indexOf("ipod") > -1) ) {
window.addEventListener('beforeinstallprompt', (event) => {
console.log('', 'beforeinstallprompt', event);
// Stash the event so it can be triggered later.
window.deferredPrompt = event;
// Remove the 'hidden' class from the install button container
divInstall.classList.toggle('hidden', false);
});
}
butInstall.addEventListener('click', async () => {
console.log('', 'butInstall-clicked');
const promptEvent = window.deferredPrompt;
if (!promptEvent) {
// The deferred prompt isn't available.
return;
}
// Show the install prompt.
promptEvent.prompt();
// Log the result
const result = await promptEvent.userChoice;
console.log('', 'userChoice', result);
// Reset the deferred prompt variable, since
// prompt() can only be called once.
window.deferredPrompt = null;
// Hide the install button.
divInstall.classList.toggle('hidden', true);
count=0;
});
window.addEventListener('appinstalled', (event) => {
console.log('', 'appinstalled', event);
// Clear the deferredPrompt so it can be garbage collected
window.deferredPrompt = null;
});
</script>
main.js
window.onload = () => {
// 'use strict';
console.log(navigator);
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('./sw.js');
}
}