24

I implemented PWA for my static site. service worker register successfully and my page is also working in offline as I expected but the real problem is in add to Home screen

I included manifest.json with appropriate icons and still, I don't see the add home screen pop up and while trying to push the add to home screen from inspected only i able to see the popup

This my site URL: https://www.savesoftinc.com/

Manifest JSON:

{
 "name": "Save Soft",
 "short_name": "SaveSoft",
  "start_url": ".",
  "display": "standalone",
  "background_color": "#fff",
  "theme_color": "#0EC3F7",
  "description": "IT Services & Solutions.",
 "icons": [
  {
   "src": "\/android-icon-36x36.png",
   "sizes": "36x36",
   "type": "image\/png",
   "density": "0.75"
  },
  {
   "src": "\/android-icon-48x48.png",
   "sizes": "48x48",
   "type": "image\/png",
   "density": "1.0"
  },
  {
   "src": "\/android-icon-72x72.png",
   "sizes": "72x72",
   "type": "image\/png",
   "density": "1.5"
  },
  {
   "src": "\/android-icon-96x96.png",
   "sizes": "96x96",
   "type": "image\/png",
   "density": "2.0"
  },
  {
   "src": "\/android-icon-144x144.png",
   "sizes": "144x144",
   "type": "image\/png",
   "density": "3.0"
  },
  {
   "src": "\/android-icon-192x192.png",
   "sizes": "192x192",
   "type": "image\/png",
   "density": "4.0"
  },
  {
   "src": "\/ms-icon-512x512.png",
   "sizes": "512x512",
   "type": "image\/png",
   "density": "5.0"
  }
 ]
}

And also try the below code to pop up the banner as suggested by google

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 notify the user they can add to home screen
  btnAdd.style.display = 'block';
});
btnAdd.addEventListener('click', (e) => {
  // hide our user interface that shows our A2HS button
  btnAdd.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;
    });
});
window.addEventListener('appinstalled', (evt) => {
  app.logEvent('a2hs', 'installed');
});

but it shows error:

Uncaught ReferenceError: btnAdd is not defined

ref:https://developers.google.com/web/fundamentals/app-install-banners/

Harish Karthick
  • 710
  • 2
  • 12
  • 26
  • 1
    I don't know the rest of your code, but the error clearly says you don't have an element called `btnAdd`. Either create a button and call the variable like that, or just call the `prompt()` inside the other event (i wouldn't recommend that). – Agash Thamo. Jul 30 '18 at 11:41
  • @AgashThamo. am trying both ways for add to home screen pop up the second method is for chrome 67+ browsers. yes i too notice that error but in as suggest google doc they didn't mention to create any button manually so only i added ref link. – Harish Karthick Jul 30 '18 at 12:05
  • You are not using "both ways" as you are preventing the default behaviour for Chrome 67 and earlier by calling `e.preventDefault()` anyways. Just try and call `e.prompt()` inside your first event for example. – Agash Thamo. Jul 30 '18 at 12:26
  • And yes, Google does not mention to add a button manually, they presume you understand that much and do so yourself. Alternatively give feedback to Google for the docs and ask them to put it in as well. – Agash Thamo. Jul 30 '18 at 13:39
  • no @AgashThamo. you don't understand and i use both ways means , in live i won't use that piece of code and the second way is introduce now only probably a month before on chrome 67 launch i tried it locally – Harish Karthick Jul 30 '18 at 14:03
  • Then do you mind updating your code in your question to reflect your real code, else we can't really help you. Just copy pasting Google's code and asking why it doesn't work won't help us much to further help you. your App Manifest file seems fine to me, so that's not the problem. I can also add your site to my Desktop using the Dev Tools, so please share the code of your real service worker or code that handels the events. – Agash Thamo. Jul 30 '18 at 14:06
  • 1
    Your site has mixed content. That may be blocking the service worker. Looks like your google fonts url is still HTTP. http://fonts.googleapis.com/css?family=PT+Sans:400,400italic,700,700italic – Mathias Jul 30 '18 at 14:49
  • The lighthouse audit tool shows that the prompt will not be shown. And also mentions that you are not loading your site via HTTPS listing the google font URL as insecure – Mathias Jul 30 '18 at 14:52
  • @Mathias seems to be a valid let me check and revert back soon – Harish Karthick Jul 31 '18 at 02:24
  • Just tried on my Android phone and the automatic chrome prompt is now showing. Next step - intercept and save the prompt to be used with a button? – Mathias Jul 31 '18 at 12:19
  • @Mathias the button need to provide by us or provide by the browser and capture the event kind of thing – Harish Karthick Aug 01 '18 at 02:30
  • The button you create to catch & save the pop-up so the user can A2HS when convenient to them. Like your code above shows. – Mathias Aug 01 '18 at 02:39
  • So we don't need to define any button or modal just need to use the piece of the above code is that right @Mathias – Harish Karthick Aug 01 '18 at 03:13
  • 1
    No. You need a button and code. Here is my tester for A2HS. You will see the button show instead of the pop-up. Https://a2hs.glitch.me – Mathias Aug 01 '18 at 03:53
  • Ok thanks for your Help @Mathias – Harish Karthick Aug 01 '18 at 05:08
  • @Mathias kindly make yours as the answer so others will get used if the faced same kinda issue – Harish Karthick Aug 05 '18 at 02:43
  • I am sure that one of the criteria required for an installable progressive web app is not met. Google has laid out the requirements to an installable PWA: Please visit and read more: [https://web.dev/install-criteria/](https://web.dev/install-criteria/) – Baraja Swargiary Jul 30 '20 at 14:05

3 Answers3

40

The first step for Add to Home Screen (A2HS) automatic pop-up testing is using the lighthouse audit tools.
You need to run the PWA audit and correct warnings there until you see
--- "User can be prompted to install the Web App"

The lighthouse audit tools are available as a tab in the Chrome dev tools or as a Chrome extension.
The extension usually has the more current features.

Once you see that message you can test the automatic pop-up message on Chrome Desktop and Android (Chrome & Edge)

Important Things To Note

After you see it the first time, to see the pop-up again you will probably need to totally clear out your browser cache and for
Edge - delete the shortcut
Chrome Desktop - uninstall the app here: chrome://apps/
Crome Android - uninstall the WebApk in your applications

Once you know the automatic A2HS popup works you can then (if desired) intercept the automatic pop-up to make it less annoying to your users. Show them a button to let them know they can A2HS when convenient for them.
As described here
https://developers.google.com/web/fundamentals/app-install-banners/

Here is my tester for A2HS.
You will see the button show instead of the automatic pop-up.

Sampath
  • 63,341
  • 64
  • 307
  • 441
Mathias
  • 4,243
  • 4
  • 25
  • 34
  • I am geeting error that windows is not define when i am adding below code. window.addEventListener("beforeinstallprompt", ev => { // Stop Chrome from asking _now_ ev.preventDefault(); // Create your custom "add to home screen" button here if needed. // Keep in mind that this event may be called multiple times, // so avoid creating multiple buttons! myCustomButton.onclick = () => ev.prompt(); }); – Ankit Mori Dec 05 '18 at 09:59
  • Thanks for nice answer @Mathias, can you please share the code or github link in details – Srikrushna Jun 03 '19 at 14:22
  • @SrikrushnaPal Here is the code for my tester. Note that it has not been updated since last summer. Most things should still work the same. https://github.com/ng-chicago/AddToHomeScreen – Mathias Jun 03 '19 at 15:45
  • @SrikrushnaPal here are the notes I wrote up about the tester https://ng-chicago.github.io/2018/06/18/add-2-home-screen/ – Mathias Jun 03 '19 at 15:47
  • @Mathias could you help me for this question: https://stackoverflow.com/questions/56863293/pwa-cache-for-xml-based-frameworks – Harish Karthick Jul 12 '19 at 02:14
  • @HarishKarthick No sorry, I don't use Workbox – Mathias Jul 12 '19 at 10:36
  • @Mathias thanks did you know someone to answer this – Harish Karthick Jul 13 '19 at 10:06
  • can add this button for adding app on home for react pwa? – Omer Aug 28 '19 at 10:35
  • Sure @Omer. This article may help you. https://developers.google.com/web/fundamentals/app-install-banners/ – Mathias Aug 28 '19 at 11:16
  • 1
    this info `chrome://apps/` saved my time. My mobile`s popup is working fine, but I was wondering why in my desktop did not display any installer. Then, I realized I had only deleted the icon and not uninstalled it and kept running in the apps list... – Luis Febro Jan 27 '20 at 22:04
  • I tried the script but didn't works. What did I miss? https://smkn1paringin.sch.id/a2hs/ – frozenade Aug 30 '20 at 14:03
  • @frozenade if you run the Chrome Lighthouse tool, you will see there are some things you need to fix to make your website an installable PWA – Mathias Aug 30 '20 at 22:23
  • @Mathias This is what I got: - Current page does not respond with a 200 when offline - start_url does not respond with a 200 when offline. The start_url did respond, but not via a service worker. - Does not register a service worker that controls page and start_url – frozenade Sep 01 '20 at 02:18
  • @frozenade Expand each error - there should be a Learn More link where you can research what you need to do to make your website a valid PWA – Mathias Sep 01 '20 at 10:41
  • @Mathias I give up! I did anything to fix this and got no success. Even I tried the most simplest PWA example still cannot find the solution. Always got 200 error, https://jamesjohnson280.github.io/hello-pwa/ ---> works and https://gevarion.com/hello-pwa/ ---> a big fail – frozenade Sep 03 '20 at 15:12
  • @Mathias any idea on how to do this in Flutter dart code ? – Rahul Vyas Jan 04 '21 at 09:23
  • @RahulVyas No sorry, I have not built any fluter web apps yet – Mathias Jan 04 '21 at 12:45
  • Hi @Mathias and thank you for this great notes. Unfortunately, while everything seems to be in place, the add to home screen dialog isn't showing when openinh https://cambio.express on mobile. Any guess of why? Thank you! – Yatko Jan 31 '21 at 23:24
  • @Yatko Works for me in Chrome/Android. Perhaps if you have been testing with the save device for several iterations on the same device, you need to fully clear your cache and uninstall any previous tests? – Mathias Feb 01 '21 at 00:44
  • @Mathias thank you! The "+" icon shows on desktop for Chrome address bar--also using Chrome menu and "Install {appName}"--however, can't get it to show on Android devices. The only reason I could think of is slow 3G (we're testing in Cuba) or the [2021 requirement for an an offline fallback page](https://web.dev/install-criteria/). I'll assume it works in most countries, based on your feedback. – Yatko Feb 02 '21 at 21:13
  • If the popup was dismissed earlier, it won't show again for three months or so. To find out whether you have setup everything correctly, open the page from some other device and see whether the popup appears. Also you can rename the folder on the server to force the display again. – Polymath Oct 20 '22 at 06:36
14

All the guidelines are provided at : https://developers.google.com/web/fundamentals/app-install-banners/

Below are the points for PWA 'Add To Home Screen' banner

  1. The web app is NOT already installed.
  2. Add service worker and manifest files. service worker should be in a directory where start_url is in its scope.

(e.g. '/public/home' is in scope of '/' or '/public/')

  1. In manifest.json, prefer_related_applications is NOT set as true

  2. manifest.json includes:

    • short_name or name,
    • icons must include a 192px and a 512px sized icons,
    • start_url,
    • display must be one of: fullscreen, standalone, or minimal-ui
  3. Served over HTTPS (required for service workers)

  4. Has registered a service worker with a fetch event handler. e.g.

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

  5. Currently, the user has interacted with the domain for at least 30 seconds

  6. Code is placed to load service worker in root JS file.

function registerServiceWorker() {
  if ('serviceWorker' in navigator) {
     navigator.serviceWorker.register('/serviceWorker.js') //
        .then(function(reg){
            console.log("service worker registered")
        }).catch(function(err) {
            console.log(err)
        });
  }
  else {
    console.log("Could not find serviceWorker in navigator")
  }
}
registerServiceWorker()
  1. In html page manifest file is added

    <link rel="manifest" href="/pwa/manifest.json">

  2. Banner was not dismissed earlier(Will not appear for 3 months as per guide for mini-info-bar). You can bring it back by clearing cookies.

  3. For iOS devices, need to provide icons set in html page as per Safari Web Content Guide:. Presently 'Add to home screen' is only supported for Safari browser. You find this by clicking on share icon.

Viraj Doshi
  • 771
  • 6
  • 26
sat20786
  • 1,466
  • 1
  • 10
  • 11
  • 1
    How did you ever figure out that a `self.addEventListener('fetch', function(event) {})` was needed? I've implemented more fully-featured PWAs before, and I've read lots of documentation about it. This is the first time that I've implemented a PWA that only has add-to-home-screen functionality, and the documentation just says to include an empty service worker. I have yet to see anyone but you point out that a `fetch` event handler is necessary, even if it does nothing. Thank you! – Andrew Koster Sep 14 '19 at 04:55
  • @Andrew Koster After reading this answer and moving on with my research I came across this page https://developer.chrome.com/blog/improved-pwa-offline-detection/. Under the section "Updated offline detection logic" there is the fetch situation explained. It's a new thing so I guess the author of this answer is living in the future. – Bruno Tavares Mar 16 '21 at 14:43
-4

Try below code..

let btnAdd = document.querySelector(".btnAdd"); // .btnAdd maybe id or class

which is applied on custom prompt button

btnAdd.style.display = "block";

RKRK
  • 1,284
  • 5
  • 14
  • 18
vabi
  • 1