首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Service-worker不安装仅添加到主屏幕

Service-worker不安装仅添加到主屏幕
EN

Stack Overflow用户
提问于 2018-12-31 16:36:55
回答 1查看 522关注 0票数 0

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

EN

回答 1

Stack Overflow用户

发布于 2018-12-31 17:55:27

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

  • 已填写正确字段的web清单。
  • 要从安全(HTTPS)域提供服务的网站。
  • 代表设备上的应用程序的图标。
  • 注册到fetch eventhandler的服务工作者,以使应用程序脱机工作(目前只有适用于安卓系统的chrome需要此服务)。

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

代码语言:javascript
复制
    <link rel="manifest" href="name.webmanifest">

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

代码语言:javascript
复制
{
"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"
}

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

注意:

不同的浏览器有不同的安装标准,或者为了在安卓系统的Chrome68中触发

  • Chrome event.
  • Starting (2018年7月稳定),Chrome将不再显示add to home screen横幅。如果网站符合添加到主屏幕的标准,Chrome将显示mini-infobar.

对于A2HS对话框:

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

代码语言:javascript
复制
    <button class="add-button">Add to home screen</button>

提供一些样式

代码语言:javascript
复制
.add-button {
  position: absolute;
  top: 1px;
  left: 1px;
}

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

代码语言:javascript
复制
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;
      });
  });
});
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53985274

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档