如何在 Angular PWA 中拦截应用安装提示?

How to intercept app install prompt in Angular PWA?

我使用 Angular guidelines 创建了一个 PWA。我在拦截应用程序安装横幅时遇到问题。我正在使用此代码将其推迟到以后:

let deferredPrompt;
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;
  console.log("Intercepting the app install banner prompt");

  setTimeout(function() {
    deferredPrompt.prompt();
  }, 20000);

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

我的清单文件:

{
  "name": "TreadWill",
  "short_name": "TreadWill",
  "theme_color": "#2a3b3d",
  "background_color": "#2a3b3d",
  "display": "standalone",
  "scope": "/",
  "start_url": "/",
  "icons": [
    {
      "src": "assets/icons/icon-72x72.png",
      "sizes": "72x72",
      "type": "image/png"
    },
    {
      "src": "assets/icons/icon-96x96.png",
      "sizes": "96x96",
      "type": "image/png"
    },
    {
      "src": "assets/icons/icon-128x128.png",
      "sizes": "128x128",
      "type": "image/png"
    },
    {
      "src": "assets/icons/icon-144x144.png",
      "sizes": "144x144",
      "type": "image/png"
    },
    {
      "src": "assets/icons/icon-152x152.png",
      "sizes": "152x152",
      "type": "image/png"
    },
    {
      "src": "assets/icons/icon-192x192.png",
      "sizes": "192x192",
      "type": "image/png"
    },
    {
      "src": "assets/icons/icon-384x384.png",
      "sizes": "384x384",
      "type": "image/png"
    },
    {
      "src": "assets/icons/icon-512x512.png",
      "sizes": "512x512",
      "type": "image/png"
    }
  ]
}

当我在本地主机上尝试此代码时,console.log 中包含的消息被记录下来,但 20 秒后,我收到错误消息:

Uncaught (in promise) DOMException

这一行:

deferredPrompt.prompt();

当我托管代码并在移动设备上试用时,应用安装横幅立即显示,而不是 20 秒后显示。

我试过将这段代码放在 index.html 文件本身,一个单独的 js 文件中,然后在 index.html 文件中调用它。创建服务并在 .ts 文件中包含几乎相似的代码。没有任何效果。尽管我出于绝望尝试了 js 解决方案,但我更喜欢 Angular 解决问题的方法。理想情况下,我想捕获 'beforeinstallprompt' 事件并将其存储在全局变量中,并在不同的点提示该事件。

如何解决这个问题?

您可能做得很好,但根据 this article:
"The mini-infobar will appear when the site meets the add to home screen criteria, regardless of whether you preventDefault() on the beforeinstallprompt event or not."
所以对我来说,它也会立即显示出来。

Pete LePage (@petele) 是一个在 Twitter 上关注 A2HS 更新的好人。

这是我构建的添加到主屏幕 (A2HS) 测试器。页面底部的源代码有一个link。随意使用任何可能有用的东西。我最近没有更新到 angular 的最新版本。但它应该仍然可以正常工作,因为它是基本代码。
https://a2hs.glitch.me

Mathias 的回答中提供的链接帮助我解决了问题。我只是添加一些答案中未明确提及但可能对其他人有帮助的要点。

  • 应用安装横幅只能在某些用户 activity 上显示。例如 - 单击按钮。无法通过setTimeout提示。
  • 目前,拦截 beforeinstallprompt 并稍后在 Chrome 和 Edge 中显示它,因为 Chrome 和 Edge 在用户访问时自动触发事件地点。 Firefox 不会触发 beforeinstallprompt 事件,因此它在 Firefox 上不起作用。