skip to Main Content

I have a deployed app with a secure connection (https).
I managed to add it to my android home screen using this feature in Google Chrome:
enter image description here

The problem is that users aren’t likely to do this if I don’t add a button that does that in the app.

After a bit of research, I tried to adapt the code here to my React app.
So I transformed this:

let deferredPrompt;
const addBtn = document.querySelector(".add-button");
addBtn.style.display = "none";
window.addEventListener("beforeinstallprompt", (e) => {
  // Prevent Chrome 67 and earlier from automatically showing the prompt
  e.preventDefault();
  // Stash the event so it can be triggered later.
  deferredPrompt = e;
  // Update UI to notify the user they can add to home screen
  addBtn.style.display = "block";

  addBtn.addEventListener("click", (e) => {
    // hide our user interface that shows our A2HS button
    addBtn.style.display = "none";
    // Show the prompt
    deferredPrompt.prompt();
    // Wait for the user to respond to the 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;
    });
  });
});  

To this:

export class AddToHomeScreenButton extends Component {
  constructor() {
    super();
    this.state = {
      deferredPrompt: null,
    };
    this.onClick = this.onClick.bind(this);
  }
  componentDidMount() {
    let deferredPrompt;

    window.addEventListener("beforeinstallprompt", (e) => {
      console.log(
        "🚀 ~ file: AddToHomeScreenButton.js:46 ~ AddToHomeScreenButton ~ window.addEventListener ~ beforeinstallprompt"
      );
      // Prevent Chrome 67 and earlier from automatically showing the prompt
      e.preventDefault();
      // Stash the event so it can be triggered later.
      deferredPrompt = e;
      console.log(
        "🚀 ~ file: AddToHomeScreenButton.js:22 ~ AddToHomeScreenButton ~ window.addEventListener ~ deferredPrompt",
        deferredPrompt
      );
      this.setState({ deferredPrompt });
   
    });
  }
  onClick(e) {
    // hide our user interface that shows our A2HS button
    // addBtn.style.display = "none";
    // Show the prompt
    const { deferredPrompt } = this.state;

    console.log(
      "🚀 ~ file: AddToHomeScreenButton.js:49 ~ AddToHomeScreenButton ~ onClick ~ deferredPrompt",
      deferredPrompt
    );
    deferredPrompt.prompt();
    // Wait for the user to respond to the prompt
    deferredPrompt.userChoice.then((choiceResult) => {
      console.log(
        "🚀 ~ file: AddToHomeScreenButton.js:53 ~ AddToHomeScreenButton ~ deferredPrompt.userChoice.then ~ choiceResult",
        choiceResult
      );
      console.log(
        "🚀 ~ file: AddToHomeScreenButton.js:55 ~ AddToHomeScreenButton ~ deferredPrompt.userChoice.then ~ choiceResult.outcome",
        choiceResult.outcome
      );
      if (choiceResult.outcome === "accepted") {
        console.log("User accepted the A2HS prompt");
      } else {
        console.log("User dismissed the A2HS prompt");
      }
      this.setState({ deferredPrompt: null });
    });
  }
  render() {
    const { deferredPrompt } = this.state;

    return (
      <span>
        {!!deferredPrompt && (
          <Button
            className=".add-button"
            color="danger"
            type="button"
            onClick={this.onClick}
          >
            Add to home screen
          </Button>
        )}
      </span>
    );
  }
}

But, nothing happens and I have no idea why.
I check the console in the desktop and the code that’s inside this:

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

does not get executed.

I think this makes sense, since I believe this feature isn’t supposed to work on desktopp. But, it also doesn’t work on mobile in the deployed app.

But, as I said, I managed to add the app to my Android home screen using the chrome Add to home screen button. And it works like a native app.


I found here that there could be several reasons why the beforeinstallprompt is not getting triggered

beforeinstallprompt will only be fired when some conditions are true :

  1. The PWA must not already be installed Meets a user engagement
  2. heuristic (previously, the user had to interact with the domain for at
    least 30 seconds, this is not a requirement anymore).
  3. Your web app must include a web app manifest.
  4. Your web app must be served over a secure HTTPS connection.
  5. Has registered a service worker with a fetch event handler.

All of these conditions are met.
This is the web app manifest:

{
  "short_name": "React App",
  "name": "Create React App Sample",
  "icons": [
    {
      "src": "favicon.ico",
      "sizes": "64x64 32x32 24x24 16x16",
      "type": "image/x-icon"
    }
  ],
  "start_url": ".",
  "display": "standalone",
  "theme_color": "#000000",
  "background_color": "#ffffff"
}

And there is a service worker file:

// This optional code is used to register a service worker.
// register() is not called by default.

// This lets the app load faster on subsequent visits in production, and gives
// it offline capabilities. However, it also means that developers (and users)
// will only see deployed updates on subsequent visits to a page, after all the
// existing tabs open on the page have been closed, since previously cached
// resources are updated in the background.


const isLocalhost = Boolean(
  window.location.hostname === 'localhost' ||
    // [::1] is the IPv6 localhost address.
    window.location.hostname === '[::1]' ||
    // 127.0.0.0/8 are considered localhost for IPv4.
    window.location.hostname.match(
      /^127(?:.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
    )
);

export function register(config) {
  if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
    // The URL constructor is available in all browsers that support SW.
    const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href);
    if (publicUrl.origin !== window.location.origin) {
      // Our service worker won't work if PUBLIC_URL is on a different origin
      // from what our page is served on. This might happen if a CDN is used to
      // serve assets; see https://github.com/facebook/create-react-app/issues/2374
      return;
    }

    window.addEventListener('load', () => {
      const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;

      if (isLocalhost) {
        // This is running on localhost. Let's check if a service worker still exists or not.
        checkValidServiceWorker(swUrl, config);

        // Add some additional logging to localhost, pointing developers to the
        // service worker/PWA documentation.
      } else {
        // Is not localhost. Just register service worker
        registerValidSW(swUrl, config);
      }
    });
  }
}

function registerValidSW(swUrl, config) {
  navigator.serviceWorker
    .register(swUrl)
    .then(registration => {
      registration.onupdatefound = () => {
        const installingWorker = registration.installing;
        if (!installingWorker) {
          return;
        }
        installingWorker.onstatechange = () => {
          if (installingWorker.state === 'installed') {
            if (navigator.serviceWorker.controller) {
              // At this point, the updated precached content has been fetched,
              // but the previous service worker will still serve the older
              // content until all client tabs are closed.

              // Execute callback
              if (config && config.onUpdate) {
                config.onUpdate(registration);
              }
            } else {
              // At this point, everything has been precached.
              // It's the perfect time to display a
              // "Content is cached for offline use." message.

              // Execute callback
              if (config && config.onSuccess) {
                config.onSuccess(registration);
              }
            }
          }
        };
      };
    })
}

function checkValidServiceWorker(swUrl, config) {
  // Check if the service worker can be found. If it can't reload the page.
  fetch(swUrl, {
    headers: { 'Service-Worker': 'script' }
  })
    .then(response => {
      // Ensure service worker exists, and that we really are getting a JS file.
      const contentType = response.headers.get('content-type');
      if (
        response.status === 404 ||
        (!!contentType && contentType.indexOf('javascript') === -1)
      ) {
        // No service worker found. Probably a different app. Reload the page.
        navigator.serviceWorker.ready.then(registration => {
          registration.unregister().then(() => {
            window.location.reload();
          });
        });
      } else {
        // Service worker found. Proceed as normal.
        registerValidSW(swUrl, config);
      }
    })
}

export function unregister() {
  if ('serviceWorker' in navigator) {
    navigator.serviceWorker.ready.then(registration => {
      registration.unregister();
    });
  }
}

When I open the app on the desktop browser, this is what I see in Application>Manifest:
enter image description here
But, I suppose these aren’t relevant to the mobile phone browser. Plus, the app was indeed installed using the chrome add to home screen button. So it is installable.

Any idea how to debug why the button I added doesn’t work and how to fix it?

3

Answers


  1. Chosen as BEST ANSWER

    I realized I need to change this in

    index.js

    serviceWorker.unregister();
    

    To this

    serviceWorker.register();
    

    Now, when I check whether the service has been registered or not in the browser by opening this:

    chrome://serviceworker-internals/

    This is what I see for my domain name:

    Scope: https://www.domaine_name.com/

    Registration ID: 157

    Navigation preload enabled: false

    Navigation preload header length: 4

    Active worker:

    Installation Status: ACTIVATED

    Running Status: STOPPED

    Fetch handler existence: EXISTS

    Script: https://www.lodeep.com/service-worker.js

    Version ID: 2371

    Renderer process ID: 0

    Renderer thread ID: -1

    DevTools agent route ID: -2

    Client:

    ID: 205d301f-04c5-4c1a-bb2a-a810a8b2b2db

    URL: https://www.domain_name.com

    Notice this:

    Installation Status: ACTIVATED

    And this:

    Fetch handler existence: EXISTS

    So the condition

    Has registered a service worker with a fetch event handler.

    Is certainly met.
    However, the Add to home screen prompt is still not triggered. I see this in the console:

    enter image description here


    I used lighthouse to audit the website and I saw this:
    enter image description here

    And this may be causing the issue.


    I finally solved this! According to that error, I added this in manifest.json:

    {
        "src": "logo192.png",
        "type": "image/png",
        "sizes": "192x192"
    },
    {
        "src": "logo512.png",
        "type": "image/png",
        "sizes": "512x512"
    }
    

    And then I added the needed images. And it works like a charm :)


  2. I have tried creating PWA for the first time with references from other sources. Hope it helps you.

    Here are the steps I followed to get the expected output.

    First, create a react app with create-react-app with

    npx create-react-app pwa-app --template cra-template-pwa
    

    This will create some required files/changes for our PWA like,

    • src/serviceWorkerRegistration.js
    • src/service-worker.js
    • public/manifest.json
    • src/index.js

    Register the serviceWorker by adding this line in src/index.js

    serviceWorkerRegistration.register(); // by default it will be serviceWorkerRegistration.unregister();
    

    Open your public/manifest.json to edit app name and icons as you like.

    Now, Lets add a hook to create and call the installation prompt,

    src/AddToHomeScreen.jsx

    import * as React from "react";
    
    // Taken from: https://gist.github.com/rikukissa/cb291a4a82caa670d2e0547c520eae53
    export function useAddToHomescreenPrompt() {
      const [prompt, setState] = React.useState(null);
    
      const promptToInstall = () => {
        if (prompt) {
          return prompt.prompt();
        }
        return Promise.reject(
          new Error(
            'Tried installing before browser sent "beforeinstallprompt" event'
          )
        );
      };
    
      React.useEffect(() => {
        const ready = (e) => {
          e.preventDefault();
          setState(e);
        };
    
        window.addEventListener("beforeinstallprompt", ready);
    
        return () => {
          window.removeEventListener("beforeinstallprompt", ready);
        };
      }, []);
    
      return [prompt, promptToInstall];
    }
    

    in src/App.js (or whatever component),

    import { useAddToHomescreenPrompt } from "./AddToHomeScreen";
    

    call the hook,

    const [prompt, promptToInstall] = useAddToHomescreenPrompt();
    

    add onClick to the button,

    <button onClick={promptToInstall}>Add to Home Screen</button>
    

    Now at this point, after deploying the site the app should be installing.

    To check whether the app is installed already, add this to public/manifest.json

    "related_applications": [
       {
         "platform": "webapp",
         "url": "https://yourwebsite.com/manifest.json"
       }
    ],
    

    and use this function to find installed apps,

    src/App.js

      const [isAppInstalled, setIsAppInstalled] = useState(false);
    
      React.useEffect(() => {
        isPWAInstalled();
      }, []);
    
      const isPWAInstalled = async () => {
        if ("getInstalledRelatedApps" in window.navigator) {
          const relatedApps = await navigator.getInstalledRelatedApps();
          let installed = false;
          relatedApps.forEach((app) => {
            //if your PWA exists in the array it is installed
            console.log(app.platform, app.url);
            if (
              app.url ===
              "https://yourwebsite.com/manifest.json"
            ) {
              installed = true;
            }
          });
          setIsAppInstalled(installed);
        }
      };
    

    in render,

    return (
       <div className="App">
          <header className="App-header">
            <img src={logo} className="App-logo" alt="logo" />
            {!isAppInstalled ? (
              <button onClick={promptToInstall}>Add to Home Screen</button>
            ) : (
              <div>Thanks for installing our app</div>
            )}
            {status.map((text) => (
              <div style={{ fontSize: "14px", marginTop: "5px" }}>{text}</div>
            ))}
          </header>
        </div>
    );
    

    additionally, we can add shortcuts, screenshots in the public/manifest.json file.

    I hope i didn’t miss anything.

    My References:

    https://create-react-app.dev/docs/making-a-progressive-web-app/

    https://gist.github.com/rikukissa/cb291a4a82caa670d2e0547c520eae53

    check if user has already installed PWA to homescreen on Chrome?

    https://web.dev/install-criteria/

    Login or Signup to reply.
  3. Using Window: beforeinstallprompt event you can do:

    import React, { useState, useEffect } from 'react'
    
    const AddToHomeScreenButton = () => {
      const [prompt, setPrompt] = useState(null)
    
      useEffect(() => {
        const handler = (event) => {
          setPrompt(event)
        }
    
        window.addEventListener('beforeinstallprompt', handler)
    
        return () => {
          window.removeEventListener('beforeinstallprompt', handler)
        }
      }, [])
    
      const handleAddToHomeScreenClick = () => {
        prompt.prompt()
    
        prompt.userChoice.then((choiceResult) => {
          if (choiceResult.outcome === 'accepted') {
            console.log('The app was added to the home screen')
          } else {
            console.log('The app was not added to the home screen')
          }
        })
      }
    
      return <button onClick={handleAddToHomeScreenClick}>Add to home screen</button>
    }
    
    export default AddToHomeScreenButton
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search