PWA。如何向用户提供安装应用程序的报价?

时间:2018-12-02 01:06:55

标签: progressive-web-apps

我当然可以强制将我的pwa安装在设备上。但是,市场上现有的站点本身为用户提供了安装应用程序的机会。关于安装我的应用程序的可能性,用户将不知道他是否不想尝试(很可能他不想这样做)。

不幸的是,如何使用户获得这样的报价,我还没有弄清楚。找不到文章(可能是搜索设置不正确),对服务人员代码的分析也无济于事。

请帮助。

1 个答案:

答案 0 :(得分:1)

在Chrome移动设备上,默认提示非常明显。在台式机上,情况并非如此。

但是,Chrome实际上为此有一个事件。如果一切都是为了安装PWA,则将触发“ beforeinstallprompt”事件。您可以简单地向该事件添加一个侦听器,并使用该侦听器在页面上显示一条消息,以通知用户安装PWA的可能性。

以下示例是为Angular编写的,但是您可以了解事件的想法。

ngOnInit() {
    /**
     * The beforeinstallprompt event is only triggered in certain browsers. This event simply indicates that everything is in order
     * for the user to install the PWA. On mobile Chrome, a message is shown by default to the user, but we can also interfere and
     * block it. This way, we can show our own message, and continue the event on our own terms.
     * In this case, we store the event, and prevent it from continuing. We then show a regular <div> in the HTML, which contains the
     * question to install the PWA, and a button to do so. That button then triggers the prompt, which the user can then accept or deny.
     * The result of this prompt is mostly irrelevant to the functionality. Our code has no impact on the proceedings of the installation
     * after the user has accepted the prompt.
     * A possible usecase for the Promise resolved by the prompt, is for metrics. We can use the result to calculate how many users have
     * accepted or denied our prompts.
     */
    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.
      this.deferredPrompt = e;

      console.log('beforeinstallprompt!');
      // if askedOnce is true, no need to ask again.
      this.showPwaPrompt = !this.askedOnce;
    });
  }

  acceptPwaPrompt() {
    this.showPwaPrompt = false;
    this.askedOnce = true;
    this.deferredPrompt.prompt();  // Wait for the user to respond to the prompt
    this.deferredPrompt.userChoice.then((choiceResult) => {
      if (choiceResult.outcome === 'accepted') {
        console.log('User accepted the A2HS prompt');
      } else {
        console.log('User dismissed the A2HS prompt');
      }

      this.deferredPrompt = null;
    });
  }