check if user has already installed PWA to homescreen on Chrome?

前端 未结 5 1384
孤城傲影
孤城傲影 2020-12-24 02:04

I\'m trying to create an \"Add To Home Screen\" button on my progressive web app, as described in Chrome\'s documentation.

I\'m generally following the prescribed p

5条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-24 02:29

    HTML

    
    
    

    JAVASCRIPT

    // variable store event
    window.deferredPrompt = {};
    
    // get button with id
    const install_button = document.querySelector('#install');
    
    // if the app can be installed emit beforeinstallprompt
    window.addEventListener('beforeinstallprompt', e => {
      // this event does not fire if the application is already installed
      // then your button still hidden ;)
    
      // show button with display:block;
      install_button.style.display = 'block';
    
      // prevent default event
      e.preventDefault();
    
      // store install avaliable event
      window.deferredPrompt = e;
    
      // wait for click install button by user
      install_button.addEventListener('click', e => {
        window.deferredPrompt.prompt();
        window.deferredPrompt.userChoice.then(choiceResult => {
          if (choiceResult.outcome === 'accepted') {
            // user accept the prompt
    
            // lets hidden button
            install_button.style.display = 'none';
          } else {
            console.log('User dismissed the prompt');
          }
          window.deferredPrompt = null;
        });
      });
    });
    
    // if are standalone android OR safari
    if (window.matchMedia('(display-mode: standalone)').matches || window.navigator.standalone === true) {
      // hidden the button
      install_button.style.display = 'none';
    }
    
    // do action when finished install
    window.addEventListener('appinstalled', e => {
      console.log("success app install!");
    });
    

提交回复
热议问题