iPhone上的“添加到主屏幕”使用的Javascript?

118

是否可以使用JavaScript来模拟移动Safari书签菜单中的“添加到主屏幕”选项?

可能类似于IE的window.external.AddFavorite(location.href, document.title);吗?

8个回答

65

在Safari实现Service Worker并遵循Chrome和Firefox所制定的方向之前,无法通过编程方式将应用程序添加到主屏幕,也无法让浏览器提示用户。

然而,有一个小型库可以提示用户这样做,并且甚至指向正确的位置。非常有效。

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


1
目前来看,这是可用的最佳解决方案。 - hitautodestruct
该库[链接.../add-to0homescreen]可以使用,但是最后调用的语句应该是addToHomescreen({})。必须在括号内加上花括号,表示您不传递任何参数。 - RigidBody

58

在MobileSafari中添加任何书签的唯一方法(包括主屏幕上的书签)是使用内置UI,并且苹果没有提供从页面内部脚本执行此操作的任何方式。 实际上,我非常确定在Safari桌面版中也没有进行此操作的机制。


5
谢谢,我担心这个功能没有。我决定检查window.navigator.standalone,如果在移动Safari中运行,则敦促他们添加它。 - Kerrick
19
@David,这不适用于Web应用程序。并不是很多用户知道他们可以将书签保存到主屏幕。在我看来,添加一个链接/按钮来触发具有有用信息的对话框会更好。 - gregers
13
@David 这不是乞讨。在iOS上,Web应用可以作为本地应用运行,如果将它们添加到主屏幕,则可以全屏显示。甚至可以离线使用,因此如果我们可以使用JavaScript将其添加到主屏幕(当然要有适当的对话框),那就太棒了。 - Ákos Nikházy
3
@the_nakos这就是为什么没有一个简单的“添加到主屏幕”的方式,因为那会创造一个替代精彩的苹果应用商店,具有精彩的结账和精彩的应用内购买。这不是他们为防止这种情况所做的唯一措施。过去,全屏 Web 应用程序只能使用旧版 JavaScript 引擎,而移动版 Safari 已经运行更快的引擎。http://9to5mac.com/2014/06/03/ios-8-webkit-changes-finally-allow-all-apps-to-have-the-same-performance-as-safari/ - Pawel

8

有一个开源的JavaScript库提供了相关功能:

mobile-bookmark-bubble

移动书签气泡是一个JavaScript库,它向您的移动网络应用程序底部添加一个推广气泡,邀请用户将应用程序添加到其设备的主屏幕。该库使用HTML5本地存储来跟踪是否已经显示了推广信息,以避免不断地打扰用户。

此库的当前实现专门针对Mobile Safari,即iPhone和iPad设备上使用的Web浏览器。


2
有没有类似的东西适用于Android(或者,呃,我敢说,Blackberry)? - SnowboardBruin

7

2020年,移动Safari仍然无法实现此功能。

下一个最佳解决方案是显示添加页面到主屏幕的步骤说明。

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

// Detects if 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 should display install popup notification:
if (!hasSeenInstallPopup && isIos() && !isInStandaloneMode()) {
  showInstallMessage();
  localStorage.setItem("hasSeenInstallPopup", true);
}

enter image description here


这个自定义警告将一直显示,需要使用cookie或会话进行更多的解释,以便只为未安装应用程序的用户显示一次或每“X”天显示一次。拥有完整的代码可能会很有用 :) - gtamborero
在我看来,这是最佳答案。上面的代码基本上就是你所需要的一切。我没有添加很多东西就让它正常工作了(我正在2023年写这条评论!)。由于某种原因,我无法在iOS上让window.navigator.standalone正常工作,所以我使用return (window.matchMedia('(display-mode: standalone)').matches);来检查应用程序是否运行在独立模式下。 - Tintin81

3
在JavaScript中,这是不可能的,但是通过“Web Clips”的帮助,我们可以在iPhone上创建一个“添加到主屏幕”的图标或快捷方式(通过.mobileconfig代码文件)。

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

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

创建完mobileconfig文件后,我们可以在iPhone Safari浏览器中传递此URL以安装证书,完成后检查您的iPhone主屏幕,会有一个Web页面或Web应用程序的快捷图标。

这并没有回答问题。一旦您拥有足够的声望,您将能够评论任何帖子;相反,提供不需要询问者澄清的答案。- 来自审核 - Jeet
Jeet,请问你能解释一下我哪里错了吗?是的,这是正确的。根据脚本,不可能创建添加到主屏幕的功能,但是我们可以通过“Web剪辑”来创建,因此我们必须创建.mobileconfig文件。 - Rawan-25
感谢@jaepage提供的信息。cttapp.com是一个在线网站,您可以在其中创建自己的移动配置文件。但现在他们已经关闭了网页,所以您可以使用https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/iPhoneOTAConfiguration/ConfigurationProfileExamples/ConfigurationProfileExamples.html这个网站。不久我将创建我们自己的网络工具来代替它。 - Rawan-25
您还可以使用“Apple配置器2”创建Webclip。 - Rawan-25

2

1

简而言之:@Craig在上面给出了更好的答案。

以下是我的原始回答,但我不认为它能充分回答问题。今天,您需要尝试使用库来模拟此效果,因为A2HS不支持WebViews(PWAs)。

@Kerrick我想删除我的答案,但无法删除,因为它已被接受。

旧答案:

是的。大多数现代浏览器都支持渐进式Web应用程序的“添加到主屏幕”(或A2HS)功能。引用Mozilla Web Docs文章的话:

添加到主屏幕是现代浏览器中可用的一项功能,允许用户“安装”Web应用程序,即将其快捷方式添加到主屏幕。

另请参见:caniuse.com上的A2HS浏览器支持


很遗憾,到了2023年Safari在iOS上仍不支持此功能。 - Tintin81

0

在移动/桌面Safari上似乎仍然不可能...

可以使用beforeinstallprompt事件来触发安装提示。 此功能在iOS上不受支持。首先,使PWA可安装

// 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;
});

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 () => {
    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

对于iOS,有一种替代方法。您可以引导用户通过将应用程序添加到其主屏幕,类似于在add-to-homescreen repo中所做的方式:

我只是添加了一些代码:

    // 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

我希望它能帮助到某些人。祝你有美好的一天!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接