当前位置:网站首页>浏览器下载快捷方式到桌面(PWA)
浏览器下载快捷方式到桌面(PWA)
2022-07-31 22:50:00 【小蟹 !】
在工作中遇到这样一个需求,要在web上完成将网页制作成快捷方式保存到桌面,可以通过桌面的快捷方式直接打开该网页。问题困扰了我许久(主要是不了解还有这项技术?偶然在网上看见这项技术的名称-PWA(Progressive Web App))。本文详解如何完成这个功能
什么是PWA?
效果展示


如何实现这个功能?
目录结构

- icon.png ----图标,下载时以及到桌面/chrome:apps中展示的图标
- index.html ----html文件
- mainfest.json ----json文件,通过这个json向浏览器暴露名称、icon以及URL等,供浏览器使用
- service-work.js ----是一个可编程的 Web Worker,它就像一个位于浏览器与网络之间的客户端代理,可以拦截、处理、响应流经的 HTTP 请求
- sw.js ----一个js文件,主要吧处理了下载功能,也可将其放入html中
icon.png
- 一个图标文件,建议大小128x128及以上
index.html
- 在index.html中引入了mainfest.json文件
<link rel="manifest" href="mainfest.json">
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<!-- 引入json文件 -->
<link rel="manifest" href="mainfest.json">
</head>
<body>
<script> // 检测浏览器是否支持SW if (navigator.serviceWorker != null) {
navigator.serviceWorker.register('sw.js') .then(function (registartion) {
console.log('支持sw:', registartion.scope) }) } else {
console.log('不支持sw:') } navigator.serviceWorker.register('sw.js').then(function () {
console.log('serviceWorker registered') }).catch(function (e) {
console.log("serviceWorker Error",e); }) let deferredPrompt; window.addEventListener('beforeinstallprompt', (e) => {
// Prevent Chrome 67 and earlier from automatically showing the prompt e.preventDefault(); // Stash the event so it can be triggered later. deferredPrompt = e; window.download = function (acceptedCallbackFunction) {
// 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'); if (acceptedCallbackFunction) {
acceptedCallbackFunction(); } } else {
console.log('User dismissed the A2HS prompt'); } deferredPrompt = null; }); }; }); </script>
</body>
</html>
mainfest.json
- 包含了背景、图标、描述、url等信息,
- 各属性详解pwa-mainfest
{
"background_color": "purple",
"display": "fullscreen",
"icons": [{
"src": "icon.png",
"sizes": "256x256",
"type": "image/png"
}],
"name": "Strange elimination: online elimination",
"short_name": "Strange elimination",
"start_url": "https://localhost:5555/index.html?campaignid=webapp"
}
service-work.js
/** * Welcome to your Workbox-powered service worker! * * You'll need to register this file in your web app and you should * disable HTTP caching for this file too. * See https://goo.gl/nhQhGp * * The rest of the code is auto-generated. Please don't update this file * directly; instead, make changes to your Workbox build configuration * and re-run your build process. * See https://goo.gl/2aRDsh */
importScripts("https://storage.googleapis.com/workbox-cdn/releases/4.3.1/workbox-sw.js");
self.addEventListener('message', (event) => {
if (event.data && event.data.type === 'SKIP_WAITING') {
self.skipWaiting();
}
});
workbox.core.clientsClaim();
/** * The workboxSW.precacheAndRoute() method efficiently caches and responds to * requests for URLs in the manifest. * See https://goo.gl/S9QRab */
self.__precacheManifest = [].concat(self.__precacheManifest || []);
workbox.precaching.precacheAndRoute(self.__precacheManifest, {
});
workbox.routing.registerNavigationRoute(workbox.precaching.getCacheKeyForURL("/index.html"), {
blacklist: [/^\/_/,/\/[^\/]+\.[^\/]+$/],
});
sw.js
importScripts("service-worker.js");
self.addEventListener('install', (e) => {
console.log('sw install');
});
self.addEventListener('fetch', (e) => {
});
然后将这个目录部署到你的服务器中(需HTTPS服务)。注意json文件中的url需要和index.html文件所在url一致。打开这个url即可看见搜索框中有这个下载按钮了。成功完成后你就可以在计算机桌面看见生成了一个快捷方式。如果你是用chrome下载的,你也可以在chrome中打开chrome://apps/链接,也可以在其中找到你下载的应用

边栏推荐
- Difference Between Stateless and Stateful
- [Code Hoof Set Novice Village 600 Questions] Merge two numbers without passing a character array
- Go1.18 upgrade function - Fuzz test from scratch in Go language
- Istio introduction
- How to debug TestCafe
- hboot与recovery、boot.img、system.img
- Daily--Kali opens SSH (detailed tutorial)
- 不知道该怎么办的同步问题
- Judging decimal points and rounding of decimal operations in Golang
- UOS - WindTerm use
猜你喜欢

Unity-LineRenderer显示一条线

《ArchSummit:时代的呐喊,技术人听得到》

Payment module implementation

Go mode tidy reports an error go warning “all” matched no packages

支付模块实现

Student management system on the first day: complete login PyQt5 + MySQL5.8 exit the operation logic

C程序设计-方法与实践(清华大学出版社)习题解析

Advanced Algebra _ Proof _ Any matrix is similar to an upper triangular matrix

高等代数_证明_任何矩阵都相似于一个上三角矩阵

VOT2021比赛简介
随机推荐
什么是动态规划,什么是背包问题
消息队列存储消息数据的MySQL表格
景区手绘地图的绘制流程
(26) About menu of the top menu of Blender source code analysis
The difference between adding or not adding the ref keyword when a variable of reference type is used as a parameter in a method call in C#
面试突击69:TCP 可靠吗?为什么?
Payment module implementation
Handwritten a simple web server (B/S architecture)
基于simulink的Active anti-islanding-AFD主动反孤岛模型仿真
标段参数说明
Quick Start Tutorial for flyway
Recognize anomalies (you will understand after reading this)
Program processes and threads (concurrency and parallelism of threads) and basic creation and use of threads
新产品如何进行网络推广?
【Acwing】第62场周赛 题解
10大主流3D建模技术
Flink_CDC construction and simple use
Document management and tools in the development process
21. Support Vector Machine - Introduction to Kernel Functions
A solution to the server encountered an internal error that prevented it from fulfilling this request [easy to understand]