代码之家  ›  专栏  ›  技术社区  ›  David

检查用户是否已将PWA安装到Chrome主屏幕?

  •  8
  • David  · 技术社区  · 8 年前

    我正在尝试在我的渐进式Web应用程序上创建“添加到主屏幕”按钮,如中所述。 Chrome's documentation 。

    我通常遵循规定的模式,在这里我有一些隐藏的按钮,当Chrome beforeinstallprompt 事件激发。 一旦触发事件,我就捕获它,然后在单击我自己的安装按钮后,使用该事件开始本机安装对话框。示例代码如下:

    let deferredPrompt;
    
    window.addEventListener('beforeinstallprompt', (e) => {
      // Prevent Chrome 67 and earlier from automatically showing the prompt
      e.preventDefault();
      // Stash the event so it can be triggered later.
      deferredPrompt = e;
      // Update UI notify the user they can add to home screen
      btnAdd.style.display = 'block';
    });
    
    btnAdd.addEventListener('click', (e) => {
      // hide our user interface that shows our A2HS button
      btnAdd.style.display = 'none';
      // Show the prompt
      deferredPrompt.prompt();
      // Wait for the user to respond to the prompt
      deferredPrompt.userChoice
        .then((choiceResult) => {
          if (choiceResult.outcome === 'accepted') {
            console.log('User accepted the A2HS prompt');
          } else {
            console.log('User dismissed the A2HS prompt');
          }
          deferredPrompt = null;
        });
    });
    

    我遇到的问题是我不想显示我的安装按钮( btnAdd )如果用户已经将Web应用程序安装到他们的主屏幕上,并且我很难确定如何检查这种情况。

    我希望修改上述代码如下:

    window.addEventListener('beforeinstallprompt', (e) => {
      // Prevent Chrome 67 and earlier from automatically showing the prompt
      e.preventDefault();
      // Stash the event so it can be triggered later.
      deferredPrompt = e;
    
      // If the user has not already installed...
      deferredPrompt.userChoice
        .then(choiceResult => {
          if (choiceResult === undefined) {
            // Update UI notify the user they can add to home screen
            btnAdd.style.display = 'block';
          }
        });
    });
    

    这样,如果用户已安装,则不会显示“安装”按钮。但这似乎行不通。如果他们还没有做出选择,访问 userChoice 直接用本地对话提示用户。

    我不太确定 beforeinstallevent 有效,所以这可能不是一个好的策略。理想情况下,我希望这能像 navigator.serviceWorker.ready() 这将返回一个承诺,而不是使用浏览器事件来尝试确定何时准备好东西。

    在任何情况下,在我显示自己的主屏幕安装按钮之前,我是否有任何关于如何检查用户是否已安装到主屏幕的想法?

    编辑: 正如Mathias所评论的,在显示按钮之前检查事件就足够了。我认为我遇到的问题是使用localhost的结果,它似乎会不断地激发 安装前提示 事件,即使在安装之后,也不是预期的行为。托管代码解决了这个问题。

    1 回复  |  直到 8 年前
        1
  •  4
  •   Mathias    8 年前

    也许,在截获自动弹出窗口之前不要显示按钮?

    或
    在代码中,检查窗口是否独立
    如果是,你不需要显示按钮

    if (window.matchMedia('(display-mode: standalone)').matches) {  
        // do things here  
        // set a variable to be used when calling something  
        // e.g. call Google Analytics to track standalone use   
    }  
    

    这里是我的测试示例
    https://a2hs.glitch.me

    我的测试仪的源代码
    https://github.com/ng-chicago/AddToHomeScreen

    推荐文章