添加到主屏幕对话框未在我的网站上显示

时间:2019-06-18 12:28:42

标签: javascript progressive-web-apps

我在site中设置了渐进式Web应用程序。该网站在移动设备的底部屏幕上显示A2HS默认通知。我还需要在浏览器中设置“添加到主屏幕对话框”。我在网站的main.js文件中使用了以下代码。

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

但是对话框没有显示在浏览器中,我得到了

  

未捕获的ReferenceError:未定义btnAdd

在控制台中

。我需要在网站的任何地方添加btnAdd元素吗?
我的网站sw.js

1 个答案:

答案 0 :(得分:0)

以下代码对我有用。
js

    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
  document.getElementById("pwaa").style.display = 'block';
});
    document.getElementById("pwaa").addEventListener('click', (e) => {
  // hide our user interface that shows our A2HS button
  document.getElementById("pwaa").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;
    });
});

html

<button id="pwaa">App</button>