Javascript for "Add to Home Screen" on iPhone?
Asked Answered
O

8

119

Is it possible to use Javascript to emulate the Add to Home Screen option in Mobile Safari's bookmark menu?

Something similar to IE's window.external.AddFavorite(location.href, document.title); possibly?

Oleaceous answered 17/7, 2009 at 8:13 Comment(0)
A
1

TLDR: @Craig has a better answer above.

Below is my original answer, but I do not believe it answers the question adequately. Today I would say you'd have to try a library to emulate this effect, as A2HS is not supported in WebViews (PWAs).

@Kerrick I would like to delete my answer, but cannot as it has been accepted.

Old answer:

Yes. The majority of modern browsers support the Add to Home screen (or A2HS) feature for Progressive Web Apps. To quote the Mozilla Web Docs article:

Add to Home screen is a feature available in modern browsers that allows a user to "install" a web app, ie. add a shortcut to their Home screen.

See also: A2HS browser support at caniuse.com

Arnitaarno answered 3/8, 2022 at 23:11 Comment(1)
Sadly, this is still not supported by Safari on iOS in 2023.Sulphurbottom
H
66

Until Safari implements Service Worker and follows the direction set by Chrome and Firefox, there is no way to add your app programatically to the home screen, or to have the browser prompt the user

However, there is a small library that prompts the user to do it and even points to the right spot. Works a treat.

https://github.com/cubiq/add-to-homescreen

Hilaria answered 12/2, 2011 at 5:11 Comment(2)
Sadly, this is the best solution currently available.Urissa
The library [link .../add-to0homescreen] works, however, the final call to invoke is addToHomescreen({}); Must have curly brace inside parenthesis signifying you are passing no parameters.Dimetric
E
58

The only way to add any book marks in MobileSafari (including ones on the home screen) is with the builtin UI, and that Apples does not provide anyway to do this from scripts within a page. In fact, I am pretty sure there is no mechanism for doing this on the desktop version of Safari either.

Excommunicatory answered 17/7, 2009 at 8:24 Comment(4)
Thanks, I was afraid not. I decided to check window.navigator.standalone and urge them to add it if it in running in Mobile Safari.Oleaceous
@David Not for web-apps. It's not many users that know they can bookmark to the home screen. IMHO it would be nice with a link/button that fires the dialog with a helpful message.Slier
@David It isn't begging. Web apps on iOS can run as native apps, full screen if they are added to home screen. Even offline mode is possible so it would be cool if we can use javascript to add it to home screen (With proper dialog of corse).Dyak
@the_nakos and that's why there will never be an easy way to "add to home screen" because it would create an alternative to amazing Apple app store with amazing checkout plus amazing in-app purchases. It's not the only thing they did to prevent it. In the past full screen webapps were crippled by using only old JavaScript engine when mobile safari was already running much faster engine 9to5mac.com/2014/06/03/…Barhorst
H
9

In 2020, this is still not possible on Mobile Safari.

The next best solution is to show instructions for adding the website as a shortcut to the user's home screen.

// Check if the user has seen the message already
const hasSeenInstallPopup = localStorage.getItem("hasSeenInstallPopup");

// Detects if the device is on iOS 
const isIos = () => {
  const userAgent = window.navigator.userAgent.toLowerCase();
  return /iphone|ipad|ipod/.test( userAgent );
}

// Detects if device is in standalone mode
const isInStandaloneMode = () => ('standalone' in window.navigator) && (window.navigator.standalone);

// Checks if app should display the install popup notification:
if (!hasSeenInstallPopup && isIos() && !isInStandaloneMode()) {
  showInstallMessage();
  localStorage.setItem("hasSeenInstallPopup", true);
}

enter image description here

Halfcaste answered 28/9, 2020 at 13:0 Comment(2)
This custom alert will show all the time, it needs a bit more of explanation using cookies or sessions to show only once or every "X" days for not installed app users. It could be good to have the full code :)Dodgson
This is the best answer IMHO. The code above is basically all you need. I didn't have to add much to get it to work (I am writing this comment in 2023!). For some reason, I couldn't get window.navigator.standalone to work on iOS, so I am using return (window.matchMedia('(display-mode: standalone)').matches); to check if the app runs in standalone mode or not.Sulphurbottom
U
8

There is an open source Javascript library that offers something related : mobile-bookmark-bubble

The Mobile Bookmark Bubble is a JavaScript library that adds a promo bubble to the bottom of your mobile web application, inviting users to bookmark the app to their device's home screen. The library uses HTML5 local storage to track whether the promo has been displayed already, to avoid constantly nagging users.

The current implementation of this library specifically targets Mobile Safari, the web browser used on iPhone and iPad devices.

Untruth answered 30/9, 2010 at 13:14 Comment(1)
Is there anything similar for Android (or, ugh, dare I say, Blackberry)?Milreis
C
3

In javascript, it is not possible but yes with the help of “Web Clips” we can create a "add to home screen" icon or shortcut in iPhone( by the code file of .mobileconfig)

https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/iPhoneOTAConfiguration/ConfigurationProfileExamples/ConfigurationProfileExamples.html

http://appdistro.cttapp.com/webclip/

after create a mobileconfig file we can pass this url in iphone safari browser install certificate and after done it check your iphone home screen there is a shortcut icon of your Web page or webapp..

Caboose answered 29/8, 2017 at 6:20 Comment(4)
This does not provide an answer to the question. Once you have sufficient reputation you will be able to comment on any post; instead, provide answers that don't require clarification from the asker. - From ReviewHeliogabalus
Jeet, can you please explain me where I'm wrong Yes this is right By the script, it is not possible to create add to home screen but with the " web clip " we can create, for it we have to create .mobileconfig fileCaboose
Thanks @jaepage for it.. cttapp.com was a online website where you can create your own mobilecofig file well right now they shutdown their webpage so You can use developer.apple.com/library/content/documentation/… this website Soon I will create our own web tool for it...Caboose
You can also use "apple configuratior 2" to create a webclipCaboose
Z
2

This is also another good Home Screen script that support iphone/ipad, Mobile Safari, Android, Blackberry touch smartphones and Playbook .

https://github.com/h5bp/mobile-boilerplate/wiki/Mobile-Bookmark-Bubble

Zaibatsu answered 11/12, 2012 at 8:57 Comment(0)
A
1

TLDR: @Craig has a better answer above.

Below is my original answer, but I do not believe it answers the question adequately. Today I would say you'd have to try a library to emulate this effect, as A2HS is not supported in WebViews (PWAs).

@Kerrick I would like to delete my answer, but cannot as it has been accepted.

Old answer:

Yes. The majority of modern browsers support the Add to Home screen (or A2HS) feature for Progressive Web Apps. To quote the Mozilla Web Docs article:

Add to Home screen is a feature available in modern browsers that allows a user to "install" a web app, ie. add a shortcut to their Home screen.

See also: A2HS browser support at caniuse.com

Arnitaarno answered 3/8, 2022 at 23:11 Comment(1)
Sadly, this is still not supported by Safari on iOS in 2023.Sulphurbottom
P
0

It seems that it is still not possible on Mobile/Desktop Safari...

It's possible to trigger the install prompt using the beforeinstallprompt event. This feature is not supported on iOS. First, Making PWAs installable.

// Initialize deferredPrompt for use later to show browser install prompt.
let deferredPrompt;

window.addEventListener('beforeinstallprompt', (e) => {
  // Prevent the mini-infobar from appearing on mobile
  e.preventDefault();
  // Stash the event so it can be triggered later.
  deferredPrompt = e;
});


buttonInstall.addEventListener('click', async () => {
  if (!deferredPrompt) {
    return;
  }

  // Show the install prompt
  deferredPrompt.prompt();

  // Wait for the user to respond to the prompt
  const { outcome } = await deferredPrompt.userChoice;

  // We've used the prompt, and can't use it again, throw it away
  deferredPrompt = null;
});

Example of a React app context:

const AddToHomeScreen = () => {
  const [deferredPrompt, setDeferredPrompt] = useState(null)

  const handleBeforeInstallPrompt = useCallback((e) => {
    // Prevent the mini-infobar from appearing on mobile
    e.preventDefault()

    // Store the event for later use
    setDeferredPrompt(e)
  }, [])

  const handleAddToHomeScreenClick = async () => {
    if (deferredPrompt) {
      // Show the install prompt
      deferredPrompt.prompt()

      const choiceResult = await deferredPrompt.userChoice
      if (choiceResult.outcome === "accepted") {
        console.log("User accepted the install prompt")
      } else {
        console.log("User dismissed the install prompt")
      }

      setDeferredPrompt(null)
    } else {
      console.log("Install prompt is not available")
    }
  }

  useEffect(() => {
    window.addEventListener("beforeinstallprompt", handleBeforeInstallPrompt)

    return () => {
      window.removeEventListener("beforeinstallprompt", handleBeforeInstallPrompt)
    }
  }, [handleBeforeInstallPrompt])

  return (
      <button onClick={handleAddToHomeScreenClick}>
        Add to Home Screen
      </button>
  )
}

export default AddToHomeScreen

For iOS, there's an alternative approach. You can guide the user through the process of adding the app to their Home Screen, similar to what is done in the add-to-homescreen repo:

I just add some codes:

    // Detects if device is on iOS 
    const isIOS = /iPad|iPhone|iPod/.test(navigator.userAgent)

 else if (isIOS) {
      // Here we could notify the user to guide them in order to add the app to Home Screen.
      // You can update your UI to render a notification, popin, alert...
      console.log(
        "To add this web app to your Home Screen, open this app in Safari/Chrome and tap the Share button, then select 'Add to Home Screen'."
      )
    } 

import { useEffect, useState, useCallback } from "react"

const AddToHomeScreen = () => {
  const [deferredPrompt, setDeferredPrompt] = useState(null)

  const handleBeforeInstallPrompt = useCallback((e) => {
    // Prevent the mini-infobar from appearing on mobile
    e.preventDefault()

    // Store the event for later use
    setDeferredPrompt(e)
  }, [])

  const handleAddToHomeScreenClick = async () => {
    const isIOS = /iPad|iPhone|iPod/.test(navigator.userAgent)

    if (deferredPrompt) {
      // Show the install prompt
      deferredPrompt.prompt()

      // Wait for the user to respond to the prompt
      const choiceResult = await deferredPrompt.userChoice
      if (choiceResult.outcome === "accepted") {
        console.log("User accepted the install prompt")
      } else {
        console.log("User dismissed the install prompt")
      }
      setDeferredPrompt(null)
    } else if (isIOS) {
      // Here we could notify the user to guide them in order to add the app to Home Screen.
      // You can update your UI to render a notification, popin, alert...
      console.log(
        "To add this web app to your Home Screen, open this app in Safari and tap the Share button, then select 'Add to Home Screen'."
      )
    } else {
      console.log("Install prompt is not available")
    }
  }

  useEffect(() => {
    window.addEventListener("beforeinstallprompt", handleBeforeInstallPrompt)

    return () => {
      window.removeEventListener("beforeinstallprompt", handleBeforeInstallPrompt)
    }
  }, [handleBeforeInstallPrompt])

  return (
      <button onClick={handleAddToHomeScreenClick}>
        Add to Home Screen
      </button>
  )
}

export default AddToHomeScreen

I hope it could help someone. Have a good day!

Pirogue answered 30/8, 2023 at 11:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.