美文网首页
PWA 使用和配置说明

PWA 使用和配置说明

作者: 耦耦 | 来源:发表于2020-07-17 14:28 被阅读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

    作用

    • 能够将你浏览的网页添加到你的手机屏幕上
    • 在 Android 上能够全屏启动,不显示地址栏 ( 由于 Iphone 手机的浏览器是 Safari ,所以不支持)
    • 控制屏幕 横屏 / 竖屏 展示
    • 定义启动画面
    • 可以设置你的应用启动是从主屏幕启动还是从 URL 启动
    • 可以设置你添加屏幕上的应用程序图标、名字、图标大小

    Service Worker

    最主要的特点:

    • 一旦被 install,就永远存在,除非被 uninstall
    • 出于安全的考虑,必须在 HTTPS 环境下才能工作
    • 不能直接操作 DOM
    • 需要的时候可以直接唤醒,不需要的时候自动睡眠(有效利用资源,此处有坑)
    • 可编程拦截代理请求和返回,缓存文件,缓存的文件可以被网页进程取到(包括网络离线状态)
    • 能向客户端推送消息

    实现

    manifest.json

    • manifest使用:Web应用程序清单部署在您的HTML页面中,使用在你的文件的头部的一个链接标记:
    <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
    }
    
    • safari 上icons需要特殊处理,要在html单独添加:
    <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" />
    
    • 备注

      • icon的图标配置有一定的要求,建议使用152x152或512x512 png
      • demo完成配置后需要确保给个JS文件访问路径正常,控制台-》application-》service workers 下勾选offline,刷线页面,查看文件请求是否成功,如果失败,说明sw.js里面的cache路径配置不正确,cache没有成功。
    • PWA页面显示模式说明

    显示模式 描述 后备显示模式
    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 这种形式直接被访问到才行。

    • 注册(入口文件加载处添加,如index.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'); });
    }
    
    
    • sw.js 内添加安装处理
    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的相对路径

    • 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为例

    • 1、【Chrome 64 +】 chrome://flags/ 启用 PWA 相关设置

    • 2、安装

      • 点击 Chrome 的菜单按钮即可找到「添加至桌面」或「安装 XXX」的选项
      • 或通过「More Tools - Create Shortcut…」来创建相应的 PWA 应用,记得要在弹窗中勾选「Open as window」
    • Chrome上实现安装的必要添加
      • The web app is not already installed
      • Meets a user engagement heuristic
      • Be served over HTTPS
      • Includes a Web App Manifest that includes:
      • short_name or name
      • icons - must include a 192px and a 512pxicon // jpg格式的icons可能无法显示,建议使用PNG
      • start_url
      • display - must be one of fullscreen, standalone, or minimal-ui
      • Note: prefer_related_applications must not be present, or be false
      • Registers a service worker with a functional fetch handler

    参考


    在线demo

    相关文章

      网友评论

          本文标题:PWA 使用和配置说明

          本文链接:https://www.haomeiwen.com/subject/uiyghktx.html