รอเหตุการณ์ beforeinstallprompt
เมื่อเบราว์เซอร์เรียกใช้เหตุการณ์ beforeinstallprompt นั่นหมายความว่า
ติดตั้งเว็บแอปได้และแสดงปุ่มติดตั้ง
ต่อผู้ใช้ได้ ระบบจะทริกเกอร์เหตุการณ์ beforeinstallprompt เมื่อแอปเป็นไปตามเกณฑ์การติดตั้ง
การบันทึกเหตุการณ์ช่วยให้นักพัฒนาแอปปรับแต่งการติดตั้งและแจ้งให้ผู้ใช้ ติดตั้งเมื่อเห็นว่าเป็นเวลาที่เหมาะสมที่สุด
- คลิกรีมิกซ์เพื่อแก้ไขเพื่อให้แก้ไขโปรเจ็กต์ได้
- เพิ่มตัวแฮนเดิลเหตุการณ์ beforeinstallpromptลงในออบเจ็กต์window
- บันทึก eventเป็นตัวแปรร่วม เราจะต้องใช้ตัวแปรนี้ในภายหลังเพื่อแสดง พรอมต์
- เลิกซ่อนปุ่มติดตั้ง
รหัส:
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() จากท่าทางของผู้ใช้
- เพิ่มตัวแฮนเดิลเหตุการณ์คลิกสำหรับปุ่มติดตั้ง
- โทร prompt()ในกิจกรรมbeforeinstallpromptที่บันทึกไว้
- บันทึกผลลัพธ์ของพรอมต์
- ตั้งค่าเหตุการณ์ beforeinstallpromptที่บันทึกไว้เป็น null
- ซ่อนปุ่มติดตั้ง
รหัส:
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
เหตุการณ์
- เพิ่มตัวแฮนเดิลเหตุการณ์ appinstalledลงในออบเจ็กต์window
- บันทึกเหตุการณ์การติดตั้งไปยัง Analytics หรือกลไกอื่นๆ
รหัส:
window.addEventListener('appinstalled', (event) => {
  console.log('👍', 'appinstalled', event);
  // Clear the deferredPrompt so it can be garbage collected
  window.deferredPrompt = null;
});
อ่านเพิ่มเติม
ขอแสดงความยินดีด้วย ตอนนี้คุณติดตั้งแอปได้แล้ว
สิ่งที่คุณทำได้เพิ่มเติมมีดังนี้