Progressive Web App, 简称 PWA,是提高 Web App 的体验的一种新方法,能给用户原生应用的体验。css
PWA 能作到原生应用的体验不是靠特指某一项技术,而是通过应用一些新技术进行改进,在安全、性能和体验三个方面都有很大提高,PWA 本质上是 Web App,借助一些新技术也具有了 Native App 的一些特性,兼具 Web App 和 Native App 的优势。html
技术依赖:java
PWA应用应该是:jquery
Progressive web app advantages. To find out how to implement PWAs, consult the guides listed in the below section.webpack
强调是渐进式的,改造过程当中能够逐步进行,下降站点的改形成本,新技术支持程度不完整,跟着新技术逐步进化。 PWA 涉及到从安全、性能和体验等方面的优化,能够考虑如下步骤:git
Service Worker,是一个浏览器和network之间的代理,解决的是如何缓存页面的资产和若是在脱机状态下仍然正常工做的问题。独立于当前网页进程,有本身独立的 worker context,没有对于DOM的访问权限,与传统的API不一样,它是非阻塞的,并基于promise方法在就绪时返回结果。它不但只是离线能力,还有消息通知、添加桌面图标等功能。github
A more detailed introduction to The Service Worker Lifecycleweb
A service worker goes through three steps in its lifecycle:算法
在install Server Worker以前,要在主进程JavaScript代码里面注册它,注册是为了告诉浏览器咱们的Servic e Worker文件是哪一个,而后在后台,Service Worker就开始安装激活。chrome
注册代码能够放到html文件的
<script></script>
标签中,也能够单独放到main.js
文件在引入html文件中。
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/service-worker.js')
.then(function(registration) {
console.log('Registration successful, scope is:', registration.scope);
})
.catch(function(error) {
console.log('Service worker registration failed, error:', error);
});
}
复制代码
代码中,先检测是浏览器是否是支持Service Worker,若是支持,就用navigator.serviceWorker.register
注册,若是成功,就会在promise的 .then
里面获得registration
.
service-worker.js文件就是咱们要编写Service Worker功能的文件。
注册时,还能够指定可选参数scope,scope是Service Worker 能够以访问到的做用域,或者说是目录。
navigator.serviceWorker.register('/service-worker.js', {
scope: '/app/'
});
复制代码
代码中指定做用域是/app/
,意思就是说,Service Workder 能够控制的path是相似于app
/app/home/
/app/abbout/
等内部目录,而不能访问 /
'/images'等 /app
更上一次层的path。
若是Service Worker 已经安装了,再次注册会返回当前活动的registration对象。
chrome浏览器已经很好的支持了Service Worker的debug功能,可在浏览器输入chrome://inspect/#service-workers
查看是否注册成功了。 或者在控制台的application选项查看。
install事件绑定在Service Worker文件中,当安装成功后,install事件就会被触发。 通常咱们会在install事件里面进行缓存的处理,用到以前提到的Cahce API
,它是一个Service Worker上的全局对象[5],能够缓存网络相应的资源,并根据他们的请求生成key,这个API和浏览器标准的缓存工做原理类似,可是只是针对本身的scope域的,缓存会一直存在,知道手动清楚或者刷新。
var cacheName = 'cachev1'
self.addEventListener('install', function(event) {
event.waitUntil(
caches.open(cacheName).then(function(cache) {
return cache.addAll(
[
'/css/bootstrap.css',
'/css/main.css',
'/js/bootstrap.min.js',
'/js/jquery.min.js',
'/offline.html'
]
);
})
);
});
复制代码
event.waitUntil()
来确保,Service Worker不会在waitUntil()
执行完成以前安装完成。caches.open()
建立一个cachev1的新缓存,返回一个缓存的promise对象,当它resolved时候,咱们在then方法里面用caches.addAll
来添加想要缓存的列表,列表是一个数组,里面的URL是相对于origin的。当 Service Worker 安装完成后并进入激活状态,会触发 activate 事件。经过监听 activate 事件你能够作一些预处理,如对旧版本的更新、对无用缓存的清理等。
service-worker.js
控制着页面资源和请求的缓存,若是 js 内容有更新,当访问网站页面时浏览器获取了新的文件,逐字节比对js 文件发现不一样时它会认为有更新启动 更新算法,因而会安装新的文件并触发 install 事件。可是此时已经处于激活状态的旧的 Service Worker 还在运行,新的 Service Worker 完成安装后会进入 waiting 状态。直到全部已打开的页面都关闭,旧的 Service Worker 自动中止,新的 Service Worker 才会在接下来从新打开的页面里生效。
若是但愿在有了新版本时,全部的页面都获得及时自动更新怎么办呢?能够在 install 事件中执行 self.skipWaiting() 方法跳过 waiting 状态,而后会直接进入 activate 阶段。接着在 activate 事件发生时,经过执行 self.clients.claim() 方法,更新全部客户端上的 Service Worker。
// 安装阶段跳过等待,直接进入 active
self.addEventListener('install', function (event) {
event.waitUntil(self.skipWaiting());
});
self.addEventListener('activate', function (event) {
event.waitUntil(
Promise.all([
// 更新客户端
self.clients.claim(),
// 清理旧版本
caches.keys().then(function (cacheList) {
return Promise.all(
cacheList.map(function (cacheName) {
if (cacheName !== 'cachev1') {
return caches.delete(cacheName);
}
})
);
})
])
);
});
复制代码
当js 文件可能会由于浏览器缓存问题,当文件有了变化时,浏览器里仍是旧的文件。这会致使更新得不到响应。如遇到该问题,可尝试这么作:在 Web Server 上添加对该文件的过滤规则,不缓存或设置较短的有效期。
或者手动调用update()
来更新
navigator.serviceWorker.register('/service-worker.js').then(reg => {
// sometime later…
reg.update();
});
复制代码
能够结合localStorage来使用,没必要每次加载更新
var version = 'v1';
navigator.serviceWorker.register('/service-worker.js').then(function (reg) {
if (localStorage.getItem('sw_version') !== version) {
reg.update().then(function () {
localStorage.setItem('sw_version', version)
});
}
});
复制代码
示意图
每一个状态都会有ing
,进行态。
选择正确的存储机制对于本地设备存储和基于云的服务器存储都很是重要。 良好的存储引擎可确保以可靠的方式保存信息,并减小带宽和提高响应能力。正确的存储缓存策略是实现离线移动网页体验的核心构建基块。
存储的类别,存储的持久化,浏览器支持状况等缘由,如何更高效的存储是咱们讨论的重点。
Best Practices for Using IndexedDB
Inspect and Manage Storage, Databases, and Caches
针对于离线存储数据,建议能够有:
基本原理
上面的两个API都是异步的(IndexedDB是基于事件的,而Cache API是基于Promise的)。他们能够与web Workers
windows
service workers
一块儿使用。IndexedDB基本能够在全部浏览器环境使用(参看上面的CanIUse),Service Wokers和Cahce API的支持状况,能够经过上面的图看到,已经支持Chrome,Firefox,Opera。IndexedDB的Promise包装器隐藏了IndexedDB库自带的一些强大但同时很是复杂的machinery(例如:事务处理 transactions,架构版本schema versioning)。IndexedDB将支持observers,这个特性能够轻松实现标签之间的同步。
对于PWA,咱们能够缓存静态资源,从而使用 Cache API 编写的应用 Application Shell(JS/CSS/HTML 文件),并从 IndexedDB 填充离线页面数据。
对于Web Storage(LocalStorage/SessionStorage)是同步的,不支持 Web worker线程,而且有大小和类型(仅限字符串)的限制。
容许将站点添加至主屏幕,是 PWA 提供的一项重要功能。虽然目前部分浏览器已经支持向主屏幕添加网页快捷方式以方便用户快速打开站点,可是 PWA 添加到主屏幕的不只仅是一个网页快捷方式,它将提供更多的功能,让 PWA 具备更加原生的体验。
PWA 添加至桌面的功能实现依赖于 manifest.json
。
为了实现 PWA 应用添加至桌面的功能,除了要求站点支持 HTTPS 以外,还须要准备 manifest.json 文件去配置应用的图标、名称等信息。举个例子,一个基本的 manifest.json 应包含以下信息:
{
"name": "Easyify Docs",
"short_name": "Easyify Docs",
"start_url": "/",
"theme_color": "#FFDF00",
"background_color": "#FFDF00",
"display":"standalone",
"description": "A compilation tools for FE, built with webpack4.x, compile faster and smart, make work easier.",
"icons": [
{
"src": "./_assets/icons/32.png",
"sizes": "32x32",
"type": "image/png"
}
],
...
}
复制代码
使用 link 标签将 manifest.json 部署到 PWA 站点 HTML 页面的头部,以下所示:
<link rel="manifest" href="path-to-manifest/manifest.json">
复制代码
参数解释:
name: {string} 应用名称,用于安装横幅、启动画面显示
short_name: {string} 应用短名称,用于主屏幕显示
icons: {Array.<ImageObject>} 应用图标列表
src: {string} 图标 url
type {string=} 图标的 mime 类型,非必填项,该字段可以让浏览器快速忽略掉不支持的图标类型
sizes {string} 图标尺寸,格式为widthxheight,宽高数值以 css 的 px 为单位。若是须要填写多个尺寸,则使用空格进行间隔,如"48x48 96x96 128x128"
start_url: {string=} 应用启动地址
scope: {string} 做用域
// scope 应遵循以下规则:
//若是没有在 manifest 中设置 scope,则默认的做用域为 manifest.json 所在文件夹;
//scope 能够设置为 ../ 或者更高层级的路径来扩大PWA的做用域;
//start_url 必须在做用域范围内;
//若是 start_url 为相对地址,其根路径受 scope 所影响;
//若是 start_url 为绝对地址(以 / 开头),则该地址将永远以 / 做为根地址;
background_color: {Color} css色值 能够指定启动画面的背景颜色。
display: {string} 显示类型
//fullscreen 应用的显示界面将占满整个屏幕
//standalone 浏览器相关UI(如导航栏、工具栏等)将会被隐藏
//minimal-ui 显示形式与standalone相似,浏览器相关UI会最小化为一个按钮,不一样浏览器在实现上略有不一样
//browser 浏览器模式,与普通网页在浏览器中打开的显示一致
orientation: string 应用显示方向
//orientation属性的值有如下几种:
//landscape-primary
//landscape-secondary
//landscape
//portrait-primary
//portrait-secondary
//portrait
//natural
//any
theme_color: {Color} // css色值theme_color 属性能够指定 PWA 的主题颜色。能够经过该属性来控制浏览器 UI 的颜色。好比 PWA 启动画面上状态栏、内容页中状态栏、地址栏的颜色,会被 theme_color 所影响。
related_applications: Array.<AppInfo> 关联应用列表 能够引导用户下载原生应用
platform: {string} 应用平台
id: {string} 应用id
复制代码
咱们都是通知就是在咱们设备上弹出的消息。通知能够是本地触发的,也能够是服务器推送的,并且咱们的应用当时并无运行。消息推送可使App的更新提醒,也多是咱们感兴趣的内容。
当咱们的web能够实现push的时候,web的体验就里Native APP更近一步了。
Push Notifications 由两个API构成:
这两个API都是创建在在Service Worker API基础上的,Service Worker 在后台响应推送消息时间,并把他们传递给应用。
Notification
在建立通知以前,应该先获取用户的许可:
// main.js
Notification.requestPermission(function(status) {
console.log('Notification permission status:', status);
//status 会有三个取值default granted denied 分别表明: 默认值(每次访问页面都询问)、 容许、拒绝
});
复制代码
获取到用户的许可以后,就能够经过 showNotification()
方法来限制主应用程序的通知。
// main.js
function displayNotification() {
if (Notification.permission == 'granted') {
navigator.serviceWorker.getRegistration().then(function(reg) {
reg.showNotification('Hello world!');
});
}
}
复制代码
要注意showNotification
,在Service Woker注册对象上调用该方法。将在活动Service Worker上建立通知,以便监听与通知交互触发的事件。
showNotification
方法有可选项参数options
,用于配置通知。
// main.js
function displayNotification() {
if (Notification.permission == 'granted') {
navigator.serviceWorker.getRegistration().then(function(reg) {
var options = {
body: 'Here is a notification body!', // 对通知添加描述
icon: 'images/example.png', // 添加一个icon图像
vibrate: [100, 50, 100], // 指定通知的电话振动模式,手机将振动100ms,暂停50ms,再次振动100ms
data: {
dateOfArrival: Date.now(),
primaryKey: 1
}, // 给通知添加自定义数据,当监听到通知的时候,能够捕获到这些数据,方便使用。
actions: [
{action: 'explore', title: 'Explore this new world',
icon: 'images/checkmark.png'},
{action: 'close', title: 'Close notification',
icon: 'images/xmark.png'},
] // 自定义的操做
};
reg.showNotification('Hello world!', options);
});
}
}
复制代码
用户收到通知以后,经过对通知的操做,就会触发监听的Notifications的相关事件,好比在关闭通知的时候就会有notificationclose
事件。
// service-worker.js
self.addEventListener('notificationclick', function(e) {
var notification = e.notification;
var primaryKey = notification.data.primaryKey;
var action = e.action;
if (action === 'close') {
notification.close();
} else {
clients.openWindow('http://www.example.com');
notification.close();
}
});
复制代码
Push
通知操做要结合push,才能实现与用户的交互,主动通知、提醒用户
每一个浏览器都有一个push service
(推送服务),当用户受权当前网站的push权限的时候,就能够将当前网站订阅到浏览器的push service
。这就会建立一个订约对象,其中包含推送服务的endpoint和公钥(keys)。当下发push消息的时候,就会发送到endpoint这个URL,并用公钥进行加密,push service
就会发送到正确的客户端。
推送服务如何知道将消息发送到哪一个客户端?端点URL包含惟一标识符。此标识符用于路由您发送到正确设备的消息,并在浏览器处理时标识应处理请求的Service Worker。
推送通知和Service Worker是匹配工做的,因此要求推送通知也必须是HTTPS,这就确保了服务器和push service之间通讯是安全的,而且从push service到用户也是安全的。
可是,HTTPS不能确保push service自己是安全的。咱们必须确保从服务器发送到客户端的数据不会被任何第三方篡改或直接检查。因此必须加密服务器上的消息。
整个发送接收展现的过程
在客户端:
1.订阅推送服务
2.将订阅对象发送到服务器
在服务器:
1.生成给用户下发的数据
2.使用用户的公钥加密数据
3.使用加密数据的有效负载将数据发送的endpoint URL
消息将路由到用户的设备。唤醒浏览器,找到正确的Service Worker并调用推送事件。
1.在推送事件中接收消息数据(若是有)
2.在推送事件中执行自定义逻辑
3.显示通知
当支持推送消息的浏览器收到消息时,它会向Service Worker发送一个push
事件。咱们能够在Service Worker中建立一个 push
事件监听器来处理消息:
// service-worker.js
self.addEventListener('push', function(e) {
var options = {
body: 'This notification was generated from a push!',
icon: 'images/example.png',
vibrate: [100, 50, 100],
data: {
dateOfArrival: Date.now(),
primaryKey: '2'
},
actions: [
{action: 'explore', title: 'Explore this new world',
icon: 'images/checkmark.png'},
{action: 'close', title: 'Close',
icon: 'images/xmark.png'},
]
};
e.waitUntil(
self.registration.showNotification('Hello world!', options)
);
});
复制代码
与以前不一样的地方就是,这里监听的是push事件,以前是notification事件,而且,这里用了event.waitUntil方法来延长push事件的生命周期,到showNotification异步操做执行完成。
在发送推送消息以前,咱们必须首先订阅推送服务。订阅返回订阅对象或者是一个subscription
。它是整个过程当中很关键一个部分,咱们才能知道push发送到哪里。
// main.js
//检查是否订阅了
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('sw.js').then(function (reg) {
console.log('Service Worker Registered!', reg);
reg.pushManager.getSubscription().then(function (sub) {
if (sub === null) {
// Update UI to ask user to register for Push
console.log('Not subscribed to push service!');
} else {
// We have a subscription, update the database
console.log('Subscription object: ', sub);
}
});
})
.catch(function (err) {
console.log('Service Worker registration failed: ', err);
});
}
function subscribeUser() {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.ready.then(function (reg) {
reg.pushManager.subscribe({
userVisibleOnly: true
}).then(function (sub) {
console.log('Endpoint URL: ', sub.endpoint);
}).catch(function (e) {
if (Notification.permission === 'denied') {
console.warn('Permission for notifications was denied');
} else {
console.error('Unable to subscribe to push', e);
}
});
})
}
}
复制代码
Web Push协议是发送发往浏览器的推送消息的正式标准。它描述了如何建立推送消息,加密推送消息并将其发送到推送消息传递平台的结构和流程。该协议抽象出用户具备哪一个消息传递平台和浏览器的细节。
Web Push协议很复杂,但咱们不须要了解全部细节。浏览器自动负责使用推送服务订阅用户。做为开发人员,咱们的工做是获取订阅令牌,提取URL并向那里发送消息。
{"endpoint":"https://fcm.googleapis.com/fcm/send/dpH5lCsTSSM:APA91bHqjZxM0VImWWqDRN7U0a3AycjUf4O-byuxb_wJsKRaKvV_iKw56s16ekq6FUqoCF7k2nICUpd8fHPxVTgqLunFeVeB9lLCQZyohyAztTH8ZQL9WCxKpA6dvTG_TUIhQUFq_n",
"keys": {
"p256dh":"BLQELIDm-6b9Bl07YrEuXJ4BL_YBVQ0dvt9NQGGJxIQidJWHPNa9YrouvcQ9d7_MqzvGS9Alz60SZNCG3qfpk=",
"auth":"4vQK-SvRAN5eo-8ASlrwA=="
}
}
复制代码
一般用VSPID身份验证来识别身份。 直接上一个例子
//main.js
var endpoint;
var key;
var authSecret;
// We need to convert the VAPID key to a base64 string when we subscribe
function urlBase64ToUint8Array(base64String) {
const padding = '='.repeat((4 - base64String.length % 4) % 4);
const base64 = (base64String + padding)
.replace(/\-/g, '+')
.replace(/_/g, '/');
const rawData = window.atob(base64);
const outputArray = new Uint8Array(rawData.length);
for (let i = 0; i < rawData.length; ++i) {
outputArray[i] = rawData.charCodeAt(i);
}
return outputArray;
}
function determineAppServerKey() {
var vapidPublicKey = 'BAyb_WgaR0L0pODaR7wWkxJi__tWbM1MPBymyRDFEGjtDCWeRYS9EF7yGoCHLdHJi6hikYdg4MuYaK0XoD0qnoY';
return urlBase64ToUint8Array(vapidPublicKey);
}
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('sw.js').then(function (registration) {
return registration.pushManager.getSubscription()
.then(function (subscription) {
if (subscription) {
// We already have a subscription, let's not add them again
return;
}
return registration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: determineAppServerKey()
})
.then(function (subscription) {
var rawKey = subscription.getKey ? subscription.getKey('p256dh') : '';
key = rawKey ? btoa(String.fromCharCode.apply(null, new Uint8Array(rawKey))) : '';
var rawAuthSecret = subscription.getKey ? subscription.getKey('auth') : '';
authSecret = rawAuthSecret ?
btoa(String.fromCharCode.apply(null, new Uint8Array(rawAuthSecret))) : '';
endpoint = subscription.endpoint;
return fetch('http://localhost:3111/register', {
method: 'post',
headers: new Headers({
'content-type': 'application/json'
}),
body: JSON.stringify({
endpoint: subscription.endpoint,
key: key,
authSecret: authSecret,
}),
})
});
});
}).catch(function (err) {
// registration failed :(
console.log('ServiceWorker registration failed: ', err);
});
}
复制代码
// server.js
const webpush = require('web-push');
const express = require('express');
var bodyParser = require('body-parser');
var path = require('path');
const app = express();
// Express setup
app.use(express.static('public'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));
function saveRegistrationDetails(endpoint, key, authSecret) {
// Save the users details in a DB
}
webpush.setVapidDetails(
'mailto:contact@deanhume.com',
'BAyb_WgaR0L0pODaR7wWkxJi__tWbM1MPBymyRDFEGjtDCWeRYS9EF7yGoCHLdHJi6hikYdg4MuYaK0XoD0qnoY',
'p6YVD7t8HkABoez1CvVJ5bl7BnEdKUu5bSyVjyxMBh0'
);
// Send a message
app.post('/sendMessage', function (req, res) {
var endpoint = req.body.endpoint;
var authSecret = req.body.authSecret;
var key = req.body.key;
const pushSubscription = {
endpoint: req.body.endpoint,
keys: {
auth: authSecret,
p256dh: key
}
};
var body = 'Breaking News: Nose picking ban for Manila police';
var iconUrl = 'https://raw.githubusercontent.com/deanhume/progressive-web-apps-book/master/chapter-6/push-notifications/public/images/homescreen.png';
webpush.sendNotification(pushSubscription,
JSON.stringify({
msg: body,
url: 'http://localhost:3111/article?id=1',
icon: iconUrl,
type: 'actionMessage'
}))
.then(result => {
console.log(result);
res.sendStatus(201);
})
.catch(err => {
console.log(err);
});
});
// Register the user
app.post('/register', function (req, res) {
var endpoint = req.body.endpoint;
var authSecret = req.body.authSecret;
var key = req.body.key;
// Store the users registration details
saveRegistrationDetails(endpoint, key, authSecret);
const pushSubscription = {
endpoint: req.body.endpoint,
keys: {
auth: authSecret,
p256dh: key
}
};
var body = 'Thank you for registering';
var iconUrl = '/images/homescreen.png';
webpush.sendNotification(pushSubscription,
JSON.stringify({
msg: body,
url: 'https://localhost:3111',
icon: iconUrl,
type: 'register'
}))
.then(result => {
console.log(result);
res.sendStatus(201);
})
.catch(err => {
console.log(err);
});
});
// The server
app.listen(3111, function () {
console.log('Example app listening on port 3111!')
});
复制代码
后面再详细说整个push过程。 也能够看先Google给出的教程描述developers.google.com/web/ilt/pwa…