注: pwa 只能在https環(huán)境下才可以使用
1. 使用vue create 項(xiàng)目名稱 的可以直接使用 vue add pwa方式添加 pwa功能广凸;參考地址:?參考地址胶坠;
2. 使用webpack 創(chuàng)建的vue(不帶 vue.config.js )項(xiàng)目或其它項(xiàng)目添加pwa述呐,步驟如下:
(1)? 手動(dòng)創(chuàng)建?manifest.json (內(nèi)容在文末)? ?注 manifest.json文件必需放下項(xiàng)目根目錄下即: (域名/manifest.json 可以訪問到manifest.json文件)
(2) 手動(dòng)創(chuàng)建?sw.js?(內(nèi)容在文末);? ?注 sw.js文件必需放下項(xiàng)目根目錄下即: (域名/sw.js 可以訪問到sw.js文件)
(3) 在index.html 引入?manifest.json和sw.js?
引入manifest.json:? <link rel="manifest" href="/manifest.json">
引入sw.js:?
if (window.matchMedia('(display-mode: standalone)').matches) {
? ? ? ? console.log('display-mode is standalone');
}
if ('serviceWorker' in navigator) {?
? ? ? ? navigator.serviceWorker.register('/sw.js').then(function (registration) {
? ? ? ? ? console.log('ServiceWorker registration successful with scope: ', registration.scope);
? ? ? ? }).catch(function (err) {
? ? ? ? ? console.log('ServiceWorker registration failed: ', err);
? ? ? ? });
}
window.addEventListener("beforeinstallprompt", (e) => {
? ? ? e.preventDefault();
? ? ? window.deferredPrompt = e;
});
(4) 在?webpack.prod.conf.js 的 CopyWebpackPlugin 中添加配置(防止打包的時(shí)候編譯sw.js 和 manifest.json文件)
{
? ? ? ? from: path.resolve(__dirname, '/sw.js'),
? ? ? ? to: path.join(__dirname, '/dist'),
? ? ? ? // ignore: ['.*']
},
{
? ? ? ? from: path.resolve(__dirname, '/manifest.json'),
? ? ? ? to: path.join(__dirname, '/dist'),
? ? ? ? // ignore: ['.*']
}
配置完成,以下是?manifest.json 和 sw.js 的文件內(nèi)容
manifest.json 文件配置
{ "background_color": "#ffffff",
? "categories": [
? ? "關(guān)鍵詞1",
? ? "關(guān)鍵詞2",
? ? "關(guān)鍵詞3",
? ],
? "description": "項(xiàng)目介紹",
? "display": "standalone",
? "gcm_sender_id": "",
? "gcm_user_visible_only": true,
? "icons": [? // 必須要要192及以上尺寸的圖標(biāo)
? ? {
? ? ? "src": "/static/img/pwa/192x192.png",
? ? ? "sizes": "192x192",
? ? ? "type": "image/png"
? ? }
? ],
? "name": "項(xiàng)目名稱",
? "short_name": "項(xiàng)目名稱",
? "start_url": "/",
? "theme_color": "#ffffff",
? "scope": "/"
}
sw.js 文件配置
var cacheName = '項(xiàng)目名稱-pwa';
self.addEventListener('install', event => {
? ? event.waitUntil(
? ? ? ? caches.open(cacheName)
? ? ? ? ? .then(cache => {
? ? ? ? ? ? console.log(cache)
? ? ? ? ? ? cache.addAll(
? ? ? ? ? ? ? [
? ? ? ? ? ? ? ? ? '/',?
? ? ? ? ? ? ? ? ? './css/*',
? ? ? ? ? ? ? ? ? './index.html',
? ? ? ? ? ? ? ? ? './img/*',
? ? ? ? ? ? ? ? ? './js/*',
? ? ? ? ? ? ? ? ? './static/*',
? ? ? ? ? ? ? ])
? ? ? ? ? }
? ? ? ? ? ).then(() => self.skipWaiting())
? ? );
});
self.addEventListener('fetch', function (event) {?
? ? event.respondWith(
? ? ? caches.match(event.request)? ? ? ? ? ? ? ? ? ?
? ? ? .then(function (response) {
? ? ? ? if (response) {? ? ? ? ? ? ? ? ? ? ? ? ? ? ?
? ? ? ? ? return response;? ? ? ? ? ? ? ? ? ? ? ? ?
? ? ? ? }
? ? ? ? return fetch(event.request);? ? ? ? ? ? ? ?
? ? ? })
? ? );
});