Search code examples
javascriptprogressive-web-apps

PWA Add to Homescreen


i have create a add to homescreen with serviceworker.js and manifest, but this start's by pageload, i want to do it with a button.

<button onclick="downloadapp();">Download Web-App</button>
        
<script>
    function downloadapp(){
            
     if ('serviceWorker' in navigator) {
        console.log("Will the service worker register?");
        navigator.serviceWorker.register('service-worker.js')
          .then(function(reg){
            console.log("Yes, it did.");
         }).catch(function(err) {
            console.log("No it didn't. This happened:", err)
        });
     }
     
        }
</scirpt>

This is not working.


Solution

  • First of all for handling the Install option you need the service worker to be installed already. I suppose you want to add a customized button to install your web application for that you can add some event listeners as following

    Your code needed to be updated with

    <script>
         if ('serviceWorker' in navigator) {
            console.log("Will the service worker register?");
            navigator.serviceWorker.register('service-worker.js')
              .then(function(reg){
                console.log("Yes, it did.");
             }).catch(function(err) {
                console.log("No it didn't. This happened:", err)
            });
         }
    </script>
    

    Code to handle service worker status and install event

    <script>
        window.addEventListener("beforeinstallprompt", (e) => {
            // Prevent the mini-infobar from appearing on mobile
            e.preventDefault();
    
            // Stash the event so it can be triggered later.
            window.deferredPrompt = e;
            console.log("Registerd event");
            // Update UI notify the user they can install the PWA
            window.localStorage.setItem("pwainstalled", "false");
            //this.showInstallPromotion();
        });
        window.addEventListener("appinstalled", (evt) => {
            // Log install to analytics
            console.log("INSTALL: Success");
            window.localStorage.setItem("pwainstalled", "true");
        });
    </script>
    

    Functions to manage and display button of install

    <script>
        function installButtonDisplay() {
            var btn = document.createElement("BUTTON");
            btn.setAttribute("id", "install-button");
            btn.innerHTML = "Download Web-App";
            btn.onclick = function() {
              installPWA();
            }
            document.body.appendChild(btn);
        }
        function installPWA() {
            if (window.deferredPrompt) {
                console.log("inside window.deferredPromp if condition");
                window.deferredPrompt.prompt();
                window.deferredPrompt.userChoice.then((choiceResult) => {
                   if (choiceResult.outcome === "accepted") { 
                      removeButton();                   
                      console.log("User accepted the install prompt");
                   } else {
                      isInstalledState(false);
                      console.log("User dismissed the install prompt");
                   }
               });
            }
        }
        function removeButton() {
            var elem = document.getElementById('install-button');
            elem.parentNode.removeChild(elem);
        }
    </script>
    

    Note: You might need to add or remove code as per your use case, this is just for reference and better understanding.