Ведомство общественных работКак сделать предложение пользователю установить приложение? - PullRequest
0 голосов
/ 02 декабря 2018

Я, конечно, могу принудительно установить мой pwa на устройство.Однако существующие на рынке сайты сами предлагают пользователю установить приложение.А по поводу возможности установки моего приложения пользователь не узнает, не хочет ли он попробовать (скорее всего, не захочет).

Как сделать пользователю такое предложение, к сожалению, у меня нетеще разобрался.Статьи не могли быть найдены (возможно, неправильно настроен поиск), анализ кода сервисных работников также не помог.

Помогите пожалуйста.

1 Ответ

0 голосов
/ 13 декабря 2018

На мобильном телефоне 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;
    });
  }
...