ทำให้ติดตั้งได้

รอเหตุการณ์ beforeinstallprompt

เมื่อเบราว์เซอร์เริ่มเหตุการณ์ beforeinstallprompt นั่นเป็นสัญญาณบ่งบอกว่าสามารถติดตั้งเว็บแอปได้ และสามารถแสดงปุ่มติดตั้งให้ผู้ใช้เห็นได้ ระบบจะเริ่มเหตุการณ์ beforeinstallprompt เมื่อแอปเป็นไปตามเกณฑ์ความสามารถในการติดตั้ง

การบันทึกเหตุการณ์ช่วยให้นักพัฒนาแอปปรับแต่งการติดตั้งและแจ้งให้ผู้ใช้ติดตั้งเมื่อเห็นว่าเหมาะสมที่สุดได้

  1. คลิกรีมิกซ์เพื่อแก้ไขเพื่อให้โปรเจ็กต์แก้ไขได้
  2. เพิ่มเครื่องจัดการเหตุการณ์ beforeinstallprompt ลงในออบเจ็กต์ window
  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);
});

จัดการการคลิกปุ่มติดตั้ง

หากต้องการแสดงข้อความแจ้งให้ติดตั้ง ให้เรียกใช้ prompt() ในเหตุการณ์ beforeinstallprompt ที่บันทึกไว้ การเรียก prompt() จะดำเนินการในเครื่องจัดการการคลิกปุ่มติดตั้ง เนื่องจากต้องเรียก prompt() จากท่าทางผู้ใช้

  1. เพิ่มเครื่องจัดการกิจกรรมการคลิกสำหรับปุ่มติดตั้ง
  2. โทรหา prompt() ในกิจกรรม beforeinstallprompt ที่บันทึกไว้
  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. เพิ่มตัวแฮนเดิลเหตุการณ์ appinstalled ลงในออบเจ็กต์ window
  2. บันทึกเหตุการณ์การติดตั้งลงใน Analytics หรือกลไกอื่นๆ

รหัส:

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

อ่านเพิ่มเติม

ยินดีด้วย ตอนนี้แอปของคุณติดตั้งได้แล้ว

สิ่งอื่นๆ ที่คุณทำได้มีดังนี้