설치 가능하도록 설정

이 글리치에는 웹 앱을 설치 가능하도록 하기 위한 필수 입력란이 있는 웹 매니페스트가 포함되어 있습니다.

또한 기본적으로 숨겨져 있는 설치 버튼도 있습니다.

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;
});

추가 자료

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

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