PWA downloading on Desktop but not on Mobile

Viewed 255

Morning friends.

Currently building a PWA for my application. I have managed to get it to install on a desktop from the click of a button, but on a mobile device it does not seem to work. I googled round and saw it had been mentioned that you cant use beforeinstallprompt on Mobile?

We have hooked onto the "beforeinstallprompt" event - which IS firing on desktop, so the code we posted can use "e" -> "deferredprompt.prompt()". BUT on mobile - beforeinstallprompt does not fire so we need a different way of doing the same defferedprompt.prompt() without the help of the event passed into the "beforeinstallprompt" function.

This is my current code

<script type="text/javascript">
   
    if ('serviceWorker' in navigator) {
      window.addEventListener('load', function() {
        navigator.serviceWorker.register('/sw.js').then(function(registration) {
          // Registration was successful
          console.log('ServiceWorker registration successful with scope: ', registration.scope);
        }, function(err) {
          // registration failed :(
          console.log('ServiceWorker registration failed: ', err);
        });
      });
    }

    let deferredPrompt;
    var div = document.querySelector('.add-to');
    var button = document.querySelector('.add-to-btn');
    div.style.display = 'block';

    window.addEventListener('beforeinstallprompt', (e) => 
    {
      

        e.preventDefault();
    
        deferredPrompt = e;
        div.style.display = 'block';
  
        button.addEventListener('click', (e) => 
        { 
         
       
            div.style.display = 'none';
       
            deferredPrompt.prompt();
          
            deferredPrompt.userChoice
            .then((choiceResult) => 
            {
                if (choiceResult.outcome === 'accepted') 
                {
                    console.log('User accepted the A2HS prompt');
                } 
                else 
                {
                    console.log('User dismissed the A2HS prompt');
                }
                deferredPrompt = null;
            });
         });
    });
</script>

In a separate file for service worker I have an event listener placed (sw.js, code.below)

self.addEventListener('fetch', function(event) {});

I could be approaching this completely wrong. Any ideas or alternatives would be welcomed in order to get this working on Mobile as well as the desktop

0 Answers
Related