PWA 使用和配置說明

PWA介紹

Progressive Web App, 即漸進(jìn)式WEB應(yīng)用,簡稱PWA。

一個(gè)網(wǎng)頁添加上 App Manifest 和 Service Worker 來實(shí)現(xiàn) PWA 的安裝和離線等功能,就可以實(shí)現(xiàn)PWA應(yīng)用封裝。

摘錄:所謂的P(Progressive)這里有兩層含義,一方面是漸進(jìn)增強(qiáng),讓W(xué)EB APP的體驗(yàn)和功能能夠用漸進(jìn)增強(qiáng)的方式來更接近原生APP的體驗(yàn)及功能;另一方面是指下一代WEB技術(shù),PWA并不是描述一個(gè)技術(shù),而是一些技術(shù)的合集。


功能和特性

  • 站點(diǎn)可添加至主屏幕(通過manifest.json配置)
  • 支持離線緩存(使用技術(shù)Service Worker)
  • 實(shí)現(xiàn)消息推送

主要使用技術(shù)

manifest.json

作用

  • 能夠?qū)⒛銥g覽的網(wǎng)頁添加到你的手機(jī)屏幕上
  • 在 Android 上能夠全屏啟動(dòng),不顯示地址欄 ( 由于 Iphone 手機(jī)的瀏覽器是 Safari ,所以不支持)
  • 控制屏幕 橫屏 / 豎屏 展示
  • 定義啟動(dòng)畫面
  • 可以設(shè)置你的應(yīng)用啟動(dòng)是從主屏幕啟動(dòng)還是從 URL 啟動(dòng)
  • 可以設(shè)置你添加屏幕上的應(yīng)用程序圖標(biāo)、名字、圖標(biāo)大小

Service Worker

最主要的特點(diǎn):

  • 一旦被 install,就永遠(yuǎn)存在,除非被 uninstall
  • 出于安全的考慮,必須在 HTTPS 環(huán)境下才能工作
  • 不能直接操作 DOM
  • 需要的時(shí)候可以直接喚醒,不需要的時(shí)候自動(dòng)睡眠(有效利用資源,此處有坑)
  • 可編程攔截代理請(qǐng)求和返回,緩存文件,緩存的文件可以被網(wǎng)頁進(jìn)程取到(包括網(wǎng)絡(luò)離線狀態(tài))
  • 能向客戶端推送消息

實(shí)現(xiàn)

manifest.json

  • manifest使用:Web應(yīng)用程序清單部署在您的HTML頁面中,使用在你的文件的頭部的一個(gè)鏈接標(biāo)記:
<link rel="manifest" href="/manifest.json">   // manifest后綴名可更改,如manifest.webmanifest
  • 配置說明
{
  "name": "GreandStream PWA ",     //顯示的插件名稱
  "short_name": "GS_PWA",          // 在APP launcher和新的tab頁顯示,如果沒有設(shè)置,則使用name
  "description": "The app that helps you understand PWA", //用于描述應(yīng)用
  "theme_color": "#2196f3",   // 桌面圖標(biāo)的背景色
  "background_color": "#2196f3",
  "display": "standalone",   // 定義開發(fā)人員對(duì)Web應(yīng)用程序的首選顯示模式。
  "icon": [          // 桌面圖標(biāo),是一個(gè)數(shù)組,注意圖片大小和格式
         {
          "src": "icon/like-152x152.png",
          "sizes": "152x152",
          "type": "image/png"
        },         
        {
            "src": "icon/like-512x512.png",
            "sizes": "512x512",
            "type": "image/png",
        }
    ],
    "start_url": "index.html"    // 應(yīng)用啟動(dòng)時(shí)的url
}
  • safari 上icons需要特殊處理,要在html單獨(dú)添加:
<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的圖標(biāo)配置有一定的要求,建議使用152x152或512x512 png
    • demo完成配置后需要確保給個(gè)JS文件訪問路徑正常,控制臺(tái)-》application-》service workers 下勾選offline,刷線頁面,查看文件請(qǐng)求是否成功,如果失敗,說明sw.js里面的cache路徑配置不正確,cache沒有成功。
  • PWA頁面顯示模式說明

顯示模式 描述 后備顯示模式
fullscreen 全屏顯示, 所有可用的顯示區(qū)域都被使用, 并且不顯示狀態(tài)欄chrome。 standalone
standalone 讓這個(gè)應(yīng)用看起來像一個(gè)獨(dú)立的應(yīng)用程序,包括具有不同的窗口,在應(yīng)用程序啟動(dòng)器中擁有自己的圖標(biāo)等。這個(gè)模式中,用戶代理將移除用于控制導(dǎo)航的UI元素,但是可以包括其他UI元素,例如狀態(tài)欄。 minimal-ui
minimal-ui 該應(yīng)用程序?qū)⒖雌饋硐褚粋€(gè)獨(dú)立的應(yīng)用程序,但會(huì)有瀏覽器地址欄。 樣式因?yàn)g覽器而異。 browser
browser 該應(yīng)用程序在傳統(tǒng)的瀏覽器標(biāo)簽或新窗口中打開,具體實(shí)現(xiàn)取決于瀏覽器和平臺(tái)。 這是默認(rèn)的設(shè)置。 (None)
  • 頁面自定義安裝導(dǎo)向提示,例如:
  1. html內(nèi)添加點(diǎn)擊按鈕
<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 文件是處于項(xiàng)目的根目錄,并且需要保證能直接通過 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 內(nèi)添加安裝處理
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的相對(duì)路徑

  • sw.js 內(nèi)添加文件獲取
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 相關(guān)設(shè)置

  • 2、安裝

    • 點(diǎn)擊 Chrome 的菜單按鈕即可找到「添加至桌面」或「安裝 XXX」的選項(xiàng)
    • 或通過「More Tools - Create Shortcut…」來創(chuàng)建相應(yīng)的 PWA 應(yīng)用,記得要在彈窗中勾選「Open as window」
  • Chrome上實(shí)現(xiàn)安裝的必要添加
    • 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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容