添加到主屏幕菜单链接

Dan*_*n W 4 javascript screen button

是否可以在我的渐进式 Web 应用程序中使用普通 Javascript 创建一个按钮,其工作方式与“添加到主屏幕”按钮相同?

例如,我的按钮会显示“单击将此应用程序添加到您的设备”,当单击时,pwa 将被添加到设备的主屏幕。

Fra*_*sco 5

您可以监听该beforeinstallprompt事件,然后在模板上显示一个按钮,如此处所述

您的代码可能如下所示:

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();
});
Run Code Online (Sandbox Code Playgroud)

如果您随后想要显示 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;
    });
});
Run Code Online (Sandbox Code Playgroud)

如果您有兴趣了解更多详细信息,我写了一系列有关渐进式 Web 应用程序的文章。