前言
有的网站存在一个下载按钮,能通过点击触发浏览器的应用安装功能。
首先要实现这个功能,需要先明白它是啥。
这其实是PWA的功能之一。中文名叫渐进式 Web 应用程序。
针对PWA本文不作过多赘述,请自行查询文档。
如何将你的web页面支持PWA
- 一个是html文件,用于展示内容,一个manifest.json文件用于描述PWA,一个service work也就是js文件。(以下是一个最基本的PWA实现)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Hello PWA</title>
<!-- 引入Web App Manifest -->
<link rel="manifest" href="/manifest.json">
</head>
<body>
<h1>Hello World</h1>
<!-- 注册Service Worker -->
<script>
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw.js')
.then(reg => console.log('ServiceWorker已注册'))
.catch(err => console.log('注册失败:', err));
}
</script>
</body>
</html>
- 要实现PWA,和普通的html文件相比,多了2个东西
- 在head中要引入manifest文件
- 在script代码块中加载sw.js,也就是service work
//manifest文件
{
"name": "Hello PWA",
"short_name": "PWA Demo",
"start_url": "/",
"display": "standalone",
"background_color": "#ffffff",
"theme_color": "#3498db",
"icons": [
{
"src": "/images/icon-512x512.png",
"type": "image/png",
"sizes": "512x512"
}
]
}
// sw.js文件
const CACHE_NAME = 'hello-pwa-v1';
const urlsToCache = ['/', '/helloworld.html'];
// 安装阶段:缓存核心资源
self.addEventListener('install', event => {
event.waitUntil(
caches.open(CACHE_NAME)
.then(cache => cache.addAll(urlsToCache))
);
});
// 拦截请求:优先返回缓存内容
self.addEventListener('fetch', event => {
event.respondWith(
caches.match(event.request)
.then(response => response || fetch(event.request))
);
});
实现下载应用功能
当浏览器检测到网站可以作为渐进式 Web 应用程序安装时,会触发 beforeinstallprompt 事件。若浏览器不支持PWA或页面本身不是PWA则不会触发。(用户已安装应用之后,也不会触发)
没有保证触发此事件的时间,但它通常发生在页面加载时。
部分支持PWA的浏览器早期版本可能会在beforeinstallprompt事件触发时,自动弹出下载弹窗。
但针对我们的项目来说,更多的是希望提供一个用户能主动触发安装的UI。
下面是一个使用 beforeinstallprompt 示例:
let deferredPrompt;
window.addEventListener('beforeinstallprompt', (e) => {
// 阻止 Chrome 67 及更早版本自动显示提示
e.preventDefault();
// 保存事件以便稍后使用
deferredPrompt = e;
// 更新 下载UI 显示到页面上
addBtn.style.display = 'block';
});
首先在全局作用域中定义了一个变量 deferredPrompt 以保存 beforeinstallprompt 事件。当 beforeinstallprompt 事件触发时,我们阻止了默认的安装提示,并将事件保存在 deferredPrompt 中。此外,我们还更新了用户界面,告诉用户他们可以安装 Web 应用程序。
然后实现自定义下载
addBtn.addEventListener('click', (e) => {
// 显示之前beforeinstallprompt保存的提示
deferredPrompt.prompt();
// 等待用户的响应以决定是否安装应用程序
deferredPrompt.userChoice.then((choiceResult) => {
if (choiceResult.outcome === 'accepted') {
console.log('用户接受了安装提示');
// 隐藏我们的下载UI
addBtn.style.display = 'none';
} else {
console.log('用户拒绝了安装提示');
}
});
});
至此完成自定义下载功能。