【问题标题】:Add to Home Screen not prompt after Beforeinstallprompt event fired触发 Beforeinstallprompt 事件后添加到主屏幕不提示
【发布时间】:2019-09-24 13:39:03
【问题描述】:

即使满足所有 PWA 规范并在 Light House 上进行检查,添加到主屏幕也不提示。

我尝试了下面的代码来检查应用程序是否已经安装。但是 appinstalled 事件没有被触发,而 beforeinstallprompt 事件被成功触发。

// 已安装应用

window.addEventListener('appinstalled', (evt) => { app.logEvent('a2hs', 'installed'); });

// 安装前提示

  window.addEventListener('beforeinstallprompt', (event) => {
   event.preventDefault();
   deferredPrompt = event;
 });```

// manifest.json

`{
    "name": "demo",
    "short_name": "demo",
    "icons": [{
            "src": "/static/public/icon/icon-192x192.png",
            "sizes": "512x512",
            "type": "image/png"
        },
        {
            "src": "/static/public/icon/icon-512x512.png",
            "sizes": "192x192",
            "type": "image/png"
        }
    ],
    "start_url": "/",
    "orientation": "portrait",
    "display": "standalone",
    "theme_color": "#085689",
    "background_color": "#085689",
    "gcm_sender_id": "103xx3xxx50x",
    "gcm_user_visible_only": true
}
`

// service worker

`self.addEventListener('fetch', (event) => {
    console.log('event', event);
});`

【问题讨论】:

  • 这是 Google Chrome 桌面版还是移动版?用户对您已构建并显示的 A2HS 的某种提示说“是”?您正在使用新设备或您在之前的测试中一直使用的设备进行测试?
  • @Mathias 感谢您的回复...这只是 google chrome 移动设备.. 我使用过新设备和旧设备.. 以前都可以使用。
  • 所以你有你自己的提示(上面的代码中没有显示)用户点击,你故意阻止自动 Chrome 迷你信息栏出现,对吧?
  • @Mathias no.. 实际上我没有显示我自己的提示,也没有阻止自动镀铬迷你吧。我也排除了之前工作的默认提示......
  • 我想你可能会阻止这个(event.preventDefault();)。在此页面上搜索 preventDefault:developers.google.com/web/fundamentals/app-install-banners

标签: manifest service-worker progressive-web-apps beforeinstallprompt


【解决方案1】:

从你的代码中删除这一行

event.preventDefault();

从 Chrome 76 开始,preventDefault() 停止了自动迷你信息栏的出现

更多详情请点击此处
https://developers.google.com/web/fundamentals/app-install-banners/

【讨论】:

【解决方案2】:
 event.preventDefault(); 

这是导致您出现问题的原因。删除它。

【讨论】:

  • 感谢您提供此代码 sn-p,它可能会提供一些有限的即时帮助。 proper explanation 将通过展示为什么这是解决问题的好方法,并使其对有其他类似问题的未来读者更有用,从而大大提高其长期价值。请edit您的回答添加一些解释,包括您所做的假设。
【解决方案3】:

通过删除event.preventDefault(),您将无法再控制该事件!

我建议以精简的方式来控制事件,并获取有关安装的信息,试试下面的代码:

window.addEventListener('beforeinstallprompt', (event) => {
   event.preventDefault();
   deferredPrompt = event;
   
   deferredPrompt.prompt();
   
   deferredPrompt.userChoice.then(result => {
          if(result.outcome === "accepted") {
            // TODO whatever you want to do when the user accept to install the app
          } else {
           // TODO whatever you want to do when the user refuse to install the app
        });
 })

【讨论】:

    猜你喜欢
    • 2019-01-26
    • 1970-01-01
    • 2022-07-26
    • 1970-01-01
    • 1970-01-01
    • 2012-07-11
    • 2018-05-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多