הגדרה כניתנת להתקנה

האזנה לאירוע beforeinstallprompt

כשהדפדפן מפעיל את האירוע beforeinstallprompt, זה הסימן שאפשר להתקין את אפליקציית האינטרנט ולהציג למשתמש לחצן התקנה. האירוע beforeinstallprompt מופעל כשהאפליקציה עומדת בקריטריונים להתקנה.

תיעוד האירוע מאפשר למפתחים להתאים אישית את ההתקנה ולהציג למשתמש בקשה להתקנה בזמן שהם חושבים שהוא הכי מתאים.

  1. לוחצים על Remix to Edit כדי להפוך את הפרויקט לעריכה.
  2. מוסיפים beforeinstallprompt event handler לאובייקט 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() מתבצעת ב-handler של לחיצה על לחצן ההתקנה כי צריך לקרוא ל-prompt() מתנועת משתמש.

  1. מוסיפים handler לאירוע קליק ללחצן ההתקנה.
  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 event handler לאובייקט window.
  2. רישום אירוע ההתקנה בניתוח הנתונים או במנגנון אחר.

קוד:

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

קריאה נוספת

מזל טוב, עכשיו אפשר להתקין את האפליקציה שלך!

הנה כמה דברים נוספים שאפשר לעשות: