首页 > 解决方案 > 服务人员不安装仅添加到主屏幕

问题描述

我正在尝试将 pwa 安装到我的移动设备上。我只能添加到主屏幕。有谁知道为什么会这样?

标签: installationprogressive-web-appsservice-workera2hs

解决方案


要使您的 PWA 可安装,您需要满足以下要求:

  • 一个网络清单,填写了正确的字段。
  • 要从安全 (HTTPS) 域提供服务的网站。
  • 代表设备上的应用程序的图标。
  • 使用 fetch 事件处理程序注册的服务工作者,以使应用程序脱机工作(目前仅适用于 Android 的 chrome 需要)。

您必须在 index.html 部分中包含清单文件,如下所示

    <link rel="manifest" href="name.webmanifest">

您的清单应包含以下字段,其中大部分是不言自明的。

{
"background_color": "purple",
  "description": "Shows random fox pictures. Hey, at least it isn't cats.",
  "display": "fullscreen",
  "icons": [
    {
      "src": "icon/fox-icon.png",
      "sizes": "192x192",
      "type": "image/png"
    }
  ],
  "name": "Awesome fox pictures",
  "short_name": "Foxes",
  "start_url": "/pwa-examples/a2hs/index.html"
}

现在,当浏览器找到满足所有要求的清单文件时,它将触发安装前提示,因此您必须显示 A2HS 对话框。

笔记:

  • 不同的浏览器有不同的安装标准,或者触发 beforeinstallprompt 事件。
  • 从 Android 版 Chrome 68(2018 年 7 月稳定版)开始,Chrome 将不再显示添加到主屏幕横幅。如果网站满足添加到主屏幕的条件,Chrome 将显示迷你信息栏。

对于 A2HS 对话框:

在您的文档中添加一个按钮,以允许用户进行安装

    <button class="add-button">Add to home screen</button>

提供一些样式

.add-button {
  position: absolute;
  top: 1px;
  left: 1px;
}

现在在注册服务工作者的 JS 文件中添加以下代码

let deferredPrompt;

//reference to your install button
const addBtn = document.querySelector('.add-button');

//We hide the button initially because the PWA will not be available for 
//install until it follows the A2HS criteria.
addBtn.style.display = 'none';

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 to notify the user they can add to home screen
  addBtn.style.display = 'block';

  addBtn.addEventListener('click', (e) => {
    // hide our user interface that shows our A2HS button
    addBtn.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;
      });
  });
});

推荐阅读