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

发布于 2024-07-27 04:34:48 字数 156 浏览 10 评论 0原文

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

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

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

原来是傀儡 2024-08-03 04:34:48

在 Safari 实现 Service Worker 并遵循 Chrome 和 Firefox 设置的方向之前,无法以编程方式将应用程序添加到主屏幕,或者让浏览器提示用户。

但是,有一个小型库可以提示用户执行以下操作:它甚至指向正确的位置。 工作是一种享受。

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

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

扛刀软妹 2024-08-03 04:34:48

在 MobileSafari 中添加任何书签(包括主屏幕上的书签)的唯一方法是使用内置 UI,而 Apple 无论如何也不提供通过页面内的脚本执行此操作的方法。 事实上,我很确定在桌面版 Safari 上也没有执行此操作的机制。

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.

帅气称霸 2024-08-03 04:34:48

到 2020 年,这在 Mobile Safari 上仍然无法实现。

下一个最佳解决方案是显示有关将网站添加为用户主屏幕快捷方式的说明。

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

输入图片此处描述

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

最单纯的乌龟 2024-08-03 04:34:48

有一个开源 Javascript 库提供了相关的东西:
mobile-bookmark-bubble

移动书签 Bubble 是一个 JavaScript 库,它会在移动 Web 应用程序的底部添加促销气泡,邀请用户将应用程序添加为书签到其设备的主屏幕。 该库使用 HTML5 本地存储来跟踪促销是否已显示,以避免不断烦扰用户。

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

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.

东北女汉子 2024-08-03 04:34:48

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

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

http://appdistro.cttapp.com/webclip/< /a>

创建 mobileconfig 文件后,我们可以在 iphone safari 浏览器安装证书中传递此 url,完成后检查你的 iphone 主屏幕,有一个网页或 web 应用程序的快捷方式图标。

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

笑饮青盏花 2024-08-03 04:34:48

这也是另一个很好的主屏幕脚本,支持 iphone/ipad、Mobile Safari、Android、Blackberry 触摸智能手机和 Playbook。

https://github.com/h5bp/mobile-boilerplate/wiki/Mobile -书签-气泡

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

嗳卜坏 2024-08-03 04:34:48

TLDR:@Craig 在上面有一个更好的答案。

以下是我的原始答案,但我认为它不能充分回答问题。 今天我想说你必须尝试一个库来模拟这种效果,因为 WebViews (PWA) 不支持 A2HS。

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

老答案:

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

“添加到主屏幕”功能可用于
现代浏览器允许用户“安装”网络应用程序,即。 添加一个
主屏幕的快捷方式。

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

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

一梦浮鱼 2024-08-03 04:34:48

似乎在移动/桌面 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

我希望它可以帮助别人。 祝你有美好的一天!

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!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文