PWA 使用和配置说明

2020-07-17  本文已影响0人  耦耦

PWA介绍

Progressive Web App, 即渐进式WEB应用,简称PWA。

一个网页添加上 App Manifest 和 Service Worker 来实现 PWA 的安装和离线等功能,就可以实现PWA应用封装。

摘录:所谓的P(Progressive)这里有两层含义,一方面是渐进增强,让WEB APP的体验和功能能够用渐进增强的方式来更接近原生APP的体验及功能;另一方面是指下一代WEB技术,PWA并不是描述一个技术,而是一些技术的合集


功能和特性


主要使用技术

manifest.json

作用

Service Worker

最主要的特点:


实现

manifest.json

<link rel="manifest" href="/manifest.json">   // manifest后缀名可更改,如manifest.webmanifest
{
  "name": "GreandStream PWA ",     //显示的插件名称
  "short_name": "GS_PWA",          // 在APP launcher和新的tab页显示,如果没有设置,则使用name
  "description": "The app that helps you understand PWA", //用于描述应用
  "theme_color": "#2196f3",   // 桌面图标的背景色
  "background_color": "#2196f3",
  "display": "standalone",   // 定义开发人员对Web应用程序的首选显示模式。
  "icon": [          // 桌面图标,是一个数组,注意图片大小和格式
         {
          "src": "icon/like-152x152.png",
          "sizes": "152x152",
          "type": "image/png"
        },         
        {
            "src": "icon/like-512x512.png",
            "sizes": "512x512",
            "type": "image/png",
        }
    ],
    "start_url": "index.html"    // 应用启动时的url
}
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-title" content="PWA test">
<link rel="shortcut icon" sizes="152x152" href="./icon/like-152x152.png">
<link rel="shortcut icon" sizes="512x512" href="./icon/like-512x512.png">
<link rel="apple-touch-icon" sizes="152x152" href="./icon/like-152x152.png" />
<link rel="apple-touch-icon" sizes="512x512" href="./icon/like-512x512.png" />
显示模式 描述 后备显示模式
fullscreen 全屏显示, 所有可用的显示区域都被使用, 并且不显示状态栏chrome。 standalone
standalone 让这个应用看起来像一个独立的应用程序,包括具有不同的窗口,在应用程序启动器中拥有自己的图标等。这个模式中,用户代理将移除用于控制导航的UI元素,但是可以包括其他UI元素,例如状态栏。 minimal-ui
minimal-ui 该应用程序将看起来像一个独立的应用程序,但会有浏览器地址栏。 样式因浏览器而异。 browser
browser 该应用程序在传统的浏览器标签或新窗口中打开,具体实现取决于浏览器和平台。 这是默认的设置。 (None)
  1. html内添加点击按钮
<button class="add-button"> + Add to home screen</button>

2.index.js添加beforeinstallprompt处理

// Code to handle install prompt on desktop

let deferredPrompt;
const addBtn = document.querySelector('.add-button');
addBtn.style.display = 'none';

window.addEventListener('beforeinstallprompt', (e) => {
    console.warn("before install prompt")
    // 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
    showInstallPromotion()
});

function showInstallPromotion(){
    console.warn("show install promotion...")
    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;
        });
    });
}

Service Worker

通常 sw.js 文件是处于项目的根目录,并且需要保证能直接通过 https: //yourhost/sw.js 这种形式直接被访问到才行。

// Register service worker to control making site work offline
if('serviceWorker' in navigator) {
    navigator.serviceWorker.register('./sw.js').then(function() { console.log('Service Worker Registered'); });
}

self.addEventListener('install', function (e) {
    console.warn("install")
    e.waitUntil(
        caches.open('fox-store').then(function (cache) {
            console.log('Opened cache');
            return cache.addAll([
                './',
                './index.html',
                './index.js',
                './style.css',
                "./icon/fox-icon.png",
                "./icon/like-152x152.png",
                "./icon/like-512x512.png",
                "./video/yewen4.mp4",
                './images/fox1.jpg',
                './images/fox2.jpg',
                './images/fox3.jpg',
                './images/fox4.jpg',
                './src/jquery.min.js',
                './src/db.js',
                './src/webSocket.js'
            ]);
        })
    );
});

注:注意cache文件路径,是sw.js的相对路径

self.addEventListener('fetch', function(e) {
    console.log(e.request.url);
    e.respondWith(
        caches.match(e.request).then(function(response) {
            return response || fetch(e.request);
        })
    );
});

使用,以chrome为例


参考


在线demo

上一篇 下一篇

猜你喜欢

热点阅读