【问题标题】:Add to home screen menu link添加到主屏幕菜单链接
【发布时间】:2019-08-21 16:06:19
【问题描述】:

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

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

【问题讨论】:

  • 您的意思是添加为书签吗?因为否则你将无法通过 JS 执行如此高权限的操作
  • 书签会将图标添加到主屏幕吗?那是我想做的,但就像你说的那样,我认为这是不可能的

标签: javascript button screen


【解决方案1】:

您可以收听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,如果您有兴趣了解更多详情。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-06
    • 2021-05-13
    • 2012-05-14
    • 1970-01-01
    相关资源
    最近更新 更多