4
4

More than 5 years have passed since last update.

PWAのホーム画面追加ポップアップを任意のデザインに変更する方法

Last updated at Posted at 2019-09-09

イメージ

  • デフォルトのポップアップデザイン

  • ポップアップを制御して(表示されないようにして)任意のデザインを充てたい

参考:Add to Home Screen
参考:Patterns for Promoting PWA Installation (mobile)

コード

example.js
function promptA2hs() {

  let deferredPrompt;

  window.addEventListener('beforeinstallprompt', (e) => {
    let btnAdd = $('#promptPwa');
    e.preventDefault();
    deferredPrompt = e;
    btnAdd.css('display', 'block');

    btnAdd.click(function (e) {
      deferredPrompt.prompt(e);
      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;
        })
    })

  });
}

この関数をサービスワーカーインストール後に記述

  window.addEventListener('load', function () {
    if ('serviceWorker' in navigator) {
      navigator.serviceWorker.register("sw.js")
        .then(function (registration) {
          console.log("sw registed.");
        }).catch(function (error) {
          console.warn("sw error.", error);
        });
    }
  });
  promptA2hs()

やっていること

  • beforeinstallpromptイベントを使います。

  • ボタンデザインのhtmlとcssは別途用意。該当箇所はcssでdisplay: noneにしておく

  • 本来ホーム画面追加のポップアップが発火するタイミングで、

    • イベント(e)をdeferredPromptという変数に入れておく(スタッシュさせておく)。
    • 該当箇所をdisplay: blockに変更
    • 該当箇所をクリックしたときにpromptdeferredPromptにスタッシュさせていたイベント発火させる。
  • 追加 or キャンセルで任意のイベントを記載。deferredPrompt.userChoice以下。(GAで追加とキャンセルの数を計りたいとき等)

参考

4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4