설치 가능하도록 설정

beforeinstallprompt 이벤트 수신

브라우저에서 beforeinstallprompt 이벤트를 발생시키면 웹 앱을 설치할 수 있고 사용자에게 설치 버튼을 표시할 수 있다는 의미입니다. beforeinstallprompt 이벤트는 앱이 설치 가능성 기준을 충족할 때 발생합니다.

이벤트를 캡처하면 개발자가 설치를 맞춤설정하고 최적의 시점이라고 판단될 때 사용자에게 설치를 요청할 수 있습니다.

  1. 리믹스하여 수정을 클릭하여 프로젝트를 수정할 수 있도록 합니다.
  2. window 객체에 beforeinstallprompt 이벤트 핸들러를 추가합니다.
  3. event를 전역 변수로 저장합니다. 나중에 프롬프트를 표시하는 데 필요합니다.
  4. 설치 버튼을 숨김 해제합니다.

코드:

window.addEventListener('beforeinstallprompt', (event) => {
  // Prevent the mini-infobar from appearing on mobile.
  event.preventDefault();
  console.log('👍', 'beforeinstallprompt', event);
  // Stash the event so it can be triggered later.
  window.deferredPrompt = event;
  // Remove the 'hidden' class from the install button container.
  divInstall.classList.toggle('hidden', false);
});

설치 버튼 클릭 처리

설치 메시지를 표시하려면 저장된 beforeinstallprompt 이벤트에서 prompt()를 호출합니다. prompt()는 사용자 동작에서 호출해야 하므로 prompt() 호출은 설치 버튼 클릭 핸들러에서 실행됩니다.

  1. 설치 버튼에 클릭 이벤트 핸들러를 추가합니다.
  2. 저장된 beforeinstallprompt 이벤트에서 prompt()을 호출합니다.
  3. 프롬프트 결과를 로깅합니다.
  4. 저장된 beforeinstallprompt 이벤트를 null로 설정합니다.
  5. 설치 버튼을 숨깁니다.

코드:

butInstall.addEventListener('click', async () => {
  console.log('👍', 'butInstall-clicked');
  const promptEvent = window.deferredPrompt;
  if (!promptEvent) {
    // The deferred prompt isn't available.
    return;
  }
  // Show the install prompt.
  promptEvent.prompt();
  // Log the result
  const result = await promptEvent.userChoice;
  console.log('👍', 'userChoice', result);
  // Reset the deferred prompt variable, since
  // prompt() can only be called once.
  window.deferredPrompt = null;
  // Hide the install button.
  divInstall.classList.toggle('hidden', true);
});

설치 이벤트 추적

설치 버튼을 통해 웹 앱을 설치하는 것은 사용자가 웹 앱을 설치할 수 있는 한 가지 방법일 뿐입니다. Chrome 메뉴, 미니 정보 표시줄, 검색주소창의 아이콘을 통해서도 사용할 수 있습니다. appinstalled 이벤트를 수신하여 이러한 모든 설치 방법을 추적할 수 있습니다.

  1. window 객체에 appinstalled 이벤트 핸들러를 추가합니다.
  2. 설치 이벤트를 분석 또는 기타 메커니즘에 로깅합니다.

코드:

window.addEventListener('appinstalled', (event) => {
  console.log('👍', 'appinstalled', event);
  // Clear the deferredPrompt so it can be garbage collected
  window.deferredPrompt = null;
});

추가 자료

축하합니다. 이제 앱을 설치할 수 있습니다.

다음과 같은 작업을 추가로 수행할 수 있습니다.