添加到主屏幕菜单 link

Add to home screen menu link

是否可以在我的 Progressive Web App 中使用 vanilla Javascript 创建一个与添加到主屏幕按钮功能相同的按钮?

例如,我的按钮会显示 "click to add this App to your device" 单击时 pwa 将添加到设备的主屏幕。

您可以收听 beforeinstallprompt 事件,然后按照 here 所述在您的模板上显示一个按钮。

您的代码可能如下所示:

window.addEventListener('beforeinstallprompt', (e) => {
  // You can save the event in order to trigger the prompt later (see below)
  deferredPrompt = e;

  // Update UI notify the user they can add to home screen.
  // With this you can show the Add to home screen button.
  showInstallPromotion();
});

如果您随后想要显示 A2HS(添加到主屏幕)对话框,您可以调用 prompt() 方法:

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;
    });
});

I wrote a series of articles 关于 Progressive Web Apps,如果你有兴趣了解更多细节。