uniapp 使用vue/pwa

复制代码
vue add @vue/pwa

src下创建service-worker.js

复制代码
/* eslint-disable no-undef*/
importScripts('https://storage.googleapis.com/workbox-cdn/releases/5.1.2/workbox-sw.js')
if (workbox) {
  console.log(`Yay! Workbox is loaded 🎉`)
} else {
  console.log(`Boo! Workbox didn't load 😬`)
}
 
workbox.core.setCacheNameDetails({
  prefix: 'ochase-search',
  suffix: 'v1.0.0'
})
workbox.core.skipWaiting() // 强制等待中的 Service Worker 被激活
workbox.core.clientsClaim() // Service Worker 被激活后使其立即获得页面控制权
workbox.precaching.precacheAndRoute(self.__precacheManifest || []) // 设置预加载
 
// 缓存web的css资源
workbox.routing.registerRoute(
  // Cache CSS files
  /.*\.css/,
  // 使用缓存,但尽快在后台更新
  new workbox.strategies.StaleWhileRevalidate({
    // 使用自定义缓存名称
    cacheName: 'css-cache'
  })
)
 
// 缓存web的js资源
workbox.routing.registerRoute(
  // 缓存JS文件
  /.*\.js/,
  // 使用缓存,但尽快在后台更新
  new workbox.strategies.StaleWhileRevalidate({
    // 使用自定义缓存名称
    cacheName: 'js-cache'
  })
)
 
// 缓存web的图片资源
workbox.routing.registerRoute(
  /\.(?:png|gif|jpg|jpeg|svg)$/,
  new workbox.strategies.StaleWhileRevalidate({
    cacheName: 'images',
    plugins: [
      new workbox.expiration.ExpirationPlugin({
        maxEntries: 60,
        maxAgeSeconds: 30 * 24 * 60 * 60 // 设置缓存有效期为30天
      })
    ]
  })
)
 
// 如果有资源在其他域名上,比如cdn、oss等,这里做单独处理,需要支持跨域
workbox.routing.registerRoute(
  /^https:\/\/cdn\.ochase\.com\/.*\.(jpe?g|png|gif|svg)/,
  new workbox.strategies.StaleWhileRevalidate({
    cacheName: 'cdn-images',
    plugins: [
      new workbox.expiration.ExpirationPlugin({
        maxEntries: 60,
        maxAgeSeconds: 5 * 24 * 60 * 60 // 设置缓存有效期为5天
      })
    ],
    fetchOptions: {
      credentials: 'include' // 支持跨域
    }
  })
)

在main.js 添加代码

复制代码
// #ifdef VUE3
import './src/registerServiceWorker'

if ('serviceWorker' in navigator) {
  window.addEventListener('load', () => {
    navigator.serviceWorker.register('/src/service-worker.js').then(registration => {
      console.log('Service Worker registered with scope:', registration.scope);
    }).catch(error => {
      console.error('Service Worker registration failed:', error);
    })
  })
}

import { createSSRApp } from 'vue'
export function createApp() {
	const app = createSSRApp(App)
	return {
		app
	}
}
// #endif

在pulic添加 manifest.json

复制代码
{
	"short_name": "name",
	"name": "name",
	"icons": [{
		"src": "/static/logo.png",
		"type": "image/png",
		"sizes": "72x72"
	},
	{
		"src": "/static/2.png",
		"type": "image/png",
		"sizes": "320x320"
	}],
	"id": "/?source=pwa",
	"start_url": "index.html",
	"background_color": "#3367D6",
	"display": "standalone",
	"scope": "/",
	"theme_color": "#3367D6",
	"shortcuts": [{
			"name": "",
			"short_name": "",
			"description": "",
			"url": "/today?source=pwa",
			"icons": [{ "src": "/static/1.png", "sizes": "96x96" }]
		},
		{
			"name": "",
			"short_name": "",
			"description": "",
			"url": "/tomorrow?source=pwa",
			"icons": [{ "src": "/static/1.png", "sizes": "96x96" }]
		}
	],
	"description": "",
	"screenshots": [{
			"src": "",
			"type": "image/png",
			"sizes": "320x320",
			"form_factor": "narrow"
		},
		{
			"src": "",
			"type": "image/jpg",
			"sizes": "320x320",
			"form_factor": "wide"
		}
	]
}

在index.html添加

复制代码
//主题颜色		
<meta name="theme-color" content="#00142A">
//引入manifest.json
<link rel="manifest" href="/public/manifest.json" />

然后运行 支持https协议和localhost

判断当前处于h5 或者pwajianti

复制代码
<script setup>
	import { onMounted } from 'vue'
	onMounted(() => {
		console.log(checkIfPWA() ? 'PWA 模式' : 'H5 模式');
		if (checkIfPWA()) {
			uni.navigateTo({
				url: '/pages/live/index'
			})
		} else {
			uni.navigateTo({
				url: '/pages/pwa/index'
			})
		}
	})

	const checkIfPWA = () => {
		return (
			window.matchMedia('(display-mode: standalone)').matches ||
			window.navigator.standalone === true ||
			document.referrer.startsWith('android-app://')
		)
	}
</script>

监听下载事件

复制代码
onMounted(() => {
  window.addEventListener('beforeinstallprompt', (event) => {
    // 防止浏览器默认的安装提示
    event.preventDefault()
    installPromptEvent.value = event;  // 保存事件对象
    console.log('安装事件已保存:', installPromptEvent.value)
  })
})

	const install = () => {
		if (installPromptEvent.value) {
			// 显示pwa安装提示
			installPromptEvent.value.prompt()

			// 监听用户选择结果
			installPromptEvent.value.userChoice.then((choiceResult) => {
				if (choiceResult.outcome === 'accepted') {
					console.log('用户接受了安装')
				} else {
					console.log('用户拒绝了安装')
				}
				installPromptEvent.value = null
			});
		} else {
			console.log('安装事件不可用')
		}
	}
相关推荐
FungLeo2 小时前
成为全栈·Vue 管理后台篇·分类树与标签管理:层级数据如何落到管理界面
前端·javascript·vue.js·分类树·naive ui·标签管理·前端数据结构
总要学点什么3 小时前
第108篇:三维特效-图片轨迹线效果——把贴图滚成一串箭头,想用它的本色反而整条消失
开发语言·javascript·ecmascript·gis·webgl·材质·cesium
ruanno_top6 小时前
选中一项后,焦点掉回了页面顶部:三个弹层的焦点还原
vue.js
小厨勺子7 小时前
我用AIUI给Rokid眼镜做了个随身换算智能体
javascript
夕水8 小时前
我用trae重构了ew-color-picker,一个插件化架构的现代颜色选择器
前端·javascript·开源
tryCbest8 小时前
Vue3——第 17 篇:模板引用(ref)与组件实例——操作 DOM 的正确姿势
vue.js·前端搭建
头发还在的女程序员9 小时前
Java在线租房系统源码解析:Spring Boot+Vue 3+UniApp房源管理与预约看房方案
java·vue.js·spring boot·租房小程序·租房系统·租房软件
FYKJ_20109 小时前
springboot同人周边订单管理系统48955-计算机毕业设计、课程设计
java·javascript·vue.js·spring boot·django·php·课程设计
总要学点什么9 小时前
第106篇:三维特效-流动线效果——让一颗光点沿整条线一路滚到头
开发语言·javascript·ecmascript·gis·webgl·材质·cesium
2分钟速写快排17 小时前
孔乙己的茴字有多少种写法?|AI 对话实时通信的三种实现
前端·javascript·github