Abdullah Ashraf
Abdullah Ashraf

Reputation: 31

Automatically create Website Shortcut to Home Page of mobile screen

I want to create a button on my website "Save this website to my phone." that when clicked will create a url shortcut (with icon, similar in appearance to a phone app) and will be placed onto the user's mobile device home screen. Clicking this icon on the phone opens the users default web browser and loads the website.

I understand this process can be done manually with several clicks, such as in this tutorial: https://www.turitop.com/blog/how-to-save-website-shortcuts-to-my-smartphone-android-ios-and-windows-mobile/ but I want to automate this functionality for my users.

Is there any way that this can be done? Thanks

Upvotes: 1

Views: 3469

Answers (1)

abraham
abraham

Reputation: 47833

Several browsers support beforeinstallprompt event for sites that meet the installability requirements. Basically if you have a manifest, the user interacted with your site, and service service worker handles fetch events beforeinstallprompt might get triggered.

You will listen for the beforeinstallprompt event. If it gets triggered you'll keep a reference to the event and show your own "install app" UI.

// This variable will save the event for later use.
let deferredPrompt;
window.addEventListener('beforeinstallprompt', (e) => {
  // Prevents the default mini-infobar or install dialog from appearing on mobile
  e.preventDefault();
  // Save the event because you'll need to trigger it later.
  deferredPrompt = e;
  // Show your customized install prompt for your PWA
  // Your own UI doesn't have to be a single element, you
  // can have buttons in different locations, or wait to prompt
  // as part of a critical journey.
  showInAppInstallPromotion();
});

When the user clicks on your custom install prompt you call the prompt method on the event and optionally check if they accepted the prompt.

// Gather the data from your custom install UI event listener
installButton.addEventListener('click', async () => {
  // deferredPrompt is a global variable we've been using in the sample to capture the `beforeinstallevent`
  deferredPrompt.prompt();
  // Find out whether the user confirmed the installation or not
  const { outcome } = await deferredPrompt.userChoice;
  // The deferredPrompt can only be used once.
  deferredPrompt = null;
  // Act on the user's choice
  if (outcome === 'accepted') {
    console.log('User accepted the install prompt.');
  } else if (outcome === 'dismissed') {
    console.log('User dismissed the install prompt');
  }
});

Upvotes: 1

Related Questions