pwa-install README

The project's README from github.com/khmyznikov/pwa-install. As one markdown file: README.md.

Published on NPM npm

<pwa-install>

New to PWAs? Unsure how to create a Web App? Check out these resources for a quick start: PWA Mozilla Docs, PWA Google Docs, PWA Builder - test and publish your PWA

Installation dialog for Progressive Web Application (PWA) and Add to Home Screen/Dock dialog for Web Apps. This offers an enhanced user experience and addresses the absence of native dialogs in certain browsers (Safari, Firefox, Opera, etc.). 39kB brotli compressed bundle. Translation/localization is supported.

✨ In-app browsers instruction support!
✨ iOS/iPadOS/MacOS 27+ support for native look and feel!
✨ Web Install API support for chromium browsers v155+

Use it as Web Component with any modern framework. No polyfill is required.

⚡Should work with any other modern framework or just vanila js as web component.

Demo

      iOS default       Install instruction       App gallery       
iOS example default iOS example install instruction iOS example gallery
MacOS 14-27+
macos_default
    iPadOS     Instruction
iPadOS example default iPadOS install instruction
In-App Detection Instagram/etc
iOS Instagramm browser iOS Telegram browser
Android Firefox/ Opera/ Others   App gallery  
Android example default Firefox Opera and others Android gallery
Chrome  App Gallery  
Chrome example default Chrome example gallery

Install

npm i @khmyznikov/pwa-install

Alternatively, you can use unpkg or esm.sh.

Import

import '@khmyznikov/pwa-install';

TS Config

"compilerOptions": {
  "moduleResolution": "Bundler",
  "types": ["dom-chromium-installation-events", "web-app-manifest"]
}

Use

<pwa-install></pwa-install>

Demo


Supported params

<pwa-install
  manual-apple
  manual-chrome
  disable-chrome
  disable-close
  use-local-storage

  install-description="Custom call to install text"
  disable-install-description
  disable-screenshots
  disable-screenshots-apple
  disable-screenshots-chrome
  manual-how-to

  disable-android-fallback

  manifest-url="/manifest.json"
  manifest-id="https://example.com/app-id"
  name="PWA"
  description="Progressive web application"         
  icon="/icon.png">
</pwa-install>

Parameter behavior

Make a good manifest file and don't use name/descr/icon params. Boolean attributes needs to be removed to act like "false"

On supported Chromium browsers, the component uses the Web Install API automatically after fetching the configured manifest. When manifest-url matches the current document's linked manifest, manifest-id is omitted, and the fetched manifest declares an id, the component uses the current-document navigator.install() signature. A different manifest or an explicit manifest-id uses navigator.install({ manifest, manifestId }). Relative manifest URLs are resolved against the current document. manifest-id is optional when the manifest declares a non-empty id.

The component continues to intercept and retain beforeinstallprompt as a legacy fallback. If both manifest-id and the fetched manifest's id are missing, the component skips Web Install and uses the retained prompt on the same click. If no compatible legacy prompt exists, pwa-install-fail-event reports a DataError. Other technical Web Install failures still require the next user click to use the retained prompt. A legacy prompt cannot install a different app.

Custom Styles

Only the Apple template supports styling, and only the tint color option is available as of today. More to come.

<!-- As attribute (JSON string) -->
<pwa-install styles='{"--tint-color": "#6366f1"}'></pwa-install>
// As property (object)
const pwaInstall = document.querySelector('pwa-install');
pwaInstall.styles = { '--tint-color': '#6366f1' };

// Or as attribute via JavaScript
pwaInstall.setAttribute('styles', JSON.stringify({ '--tint-color': '#6366f1' }));

Supported events

<script type="text/javascript">
  var pwaInstall = document.getElementsByTagName('pwa-install')[0];

  pwaInstall.addEventListener('pwa-install-success-event', (event) => {console.log(event.detail.message)});
  pwaInstall.addEventListener('pwa-install-fail-event', (event) => {
    console.log(event.detail.errorName, event.detail.fallbackAvailable);
  });
  pwaInstall.addEventListener('pwa-install-backend-event', (event) => {
    console.log(event.detail.backend, event.detail.reason);
  });
</script>

pwa-install-backend-event is dispatched immediately before an install backend is called. Its backend is web-install or beforeinstallprompt. When the legacy backend is selected, reason can be missing-manifest-id, web-install-unavailable, or web-install-failed. ⚠️ success/fail/choice events is Chromium only, iOS don't have them.

⚠️ If you see this message in the console:
Banner not shown: beforeinstallpromptevent.preventDefault() called. The page must call beforeinstallpromptevent.prompt() to show the banner.
This is not a error and not a bug. This means that the component successfully intercepted the beforeinstallprompt event.


Supported properties (readonly)

<script type="text/javascript">
  var pwaInstall = document.getElementsByTagName('pwa-install')[0];

  console.log(pwaInstall.isUnderStandaloneMode);
</script>

Supported methods

<script type="text/javascript">
  var pwaInstall = document.getElementsByTagName('pwa-install')[0];

  await pwaInstall.install();
</script>

The install method prefers navigator.install() whenever it is available and a manifest ID is configured or declared. A missing ID is detected before Web Install is called, allowing a retained beforeinstallprompt fallback to run on the same click. After a runtime Web Install failure, fallback still requires a second user click because both browser APIs consume transient user activation.

getInstalledRelatedApps is Chromium only, always empty on iOS.


Async mode

If you need to target Chromium browsers but you want to postpone component mounting, you can do it! But, need to capture beforeinstallprompt manually and pass it to the component's externalPromptEvent property(not attribute).

// capture event asap, better right in index.html script tag
window.addEventListener('beforeinstallprompt', (e) => {
  e.preventDefault();
  e.stopPropagation();
  e.stopImmediatePropagation();

  // save it somewhere
  window.promptEvent = e;
});

// later render the component on demand and pass event
document.getElementById("pwa-install").externalPromptEvent = window.promptEvent;

Supported localization

Translations available: EN, RU, TR, DE, ES, NL, EL, FR, SR, PL, ZH-CN/ZH-HK/ZH-TW, IT, UK, CS, NO/NB, PT, JA, SV, KO, KM, DA, VI, FA, HU, SK, CA-ES, HE, BG, AR, RO, TH

Language should change automatically based on browser settings. Please create the pull-request if you want to help with translation to your language. It's an easy process.

Contribution Guidelines


ROADMAP

buy me a coffee QR PayPal QR

One-time Backers ❤️

Patrick Voigt
Darren Debono
Angelo Fan
Chris Cherniakov
Moddy
Pavlo Hromadchuk
Leek Duck

pwa-install (khmyznikov/pwa-install)

Searching Database…

Что это такое?Диалог установки для Progressive Web Apps: Web Component, который показывает приглашение «Установить приложение» или «Добавить на главный экран / в Dock» в браузерах без встроенного такого приглашения — например, в Safari, Firefox или Opera.
Это фреймворк или библиотека?Библиотека, а не фреймворк: это один Web Component, который вы просто вставляете на любую страницу или в любой фреймворк (использование с React задокументировано), полифиллы не нужны. Весь бандл весит 39 килобайт в brotli-сжатии.
Как добавить его на свой сайт?Установите пакет из npm и импортируйте его как модуль или подключите напрямую с CDN unpkg или esm.sh, затем добавьте компонент на страницу и укажите на манифест вашего веб-приложения.
Приложению нужно что-то, чтобы диалог работал?Только корректный манифест веб-приложения — автор советует сделать хороший файл манифеста, а не переопределять название, описание или иконку через параметры компонента. Полифиллы и конкретный фреймворк не требуются.
Одинаково ли он работает во всех браузерах?Нет. В Chromium он использует Web Install API (v155+) или перехватывает beforeinstallprompt; на устройствах Apple показывает ручные инструкции с нативным видом на iOS/iPadOS/macOS 27+, а события успеха и ошибки срабатывают только в Chromium.
Могу ли я сам решать, когда показывать диалог?Да. Параметры вроде manual-apple и manual-chrome позволяют вызвать его самому через showDialog(), а другие отключают перехват в Chrome, делают диалог неотключаемым или запоминают выбор пользователя «больше не спрашивать» в local storage.
Можно ли оформить его под стиль моего приложения?Пока почти нет: стилизуется только шаблон для Apple, и на сегодня доступна лишь настройка цвета оттенка.
Он говорит на языке моих пользователей?Да — больше 30 встроенных переводов (EN, RU, DE, ES, ZH, JA, KO, AR и другие), язык выбирается автоматически по настройкам браузера.
Как мой код узнает, что приложение установилось?Компонент генерирует DOM-события вроде pwa-install-success-event, pwa-install-fail-event и pwa-user-choice-result-event и открывает state-свойства только для чтения, например isInstallAvailable; события успеха, ошибки и выбора работают только в Chromium.
Creator
khmyznikov
Size
11.4 MB
Stars
956
Age
5y
Commits · 90 Days