在VUE内使用beforeinstallprompt接口安装PWA添加到桌面
前提是先在网站根目录下配置一个 “manifest.json” 文件,内容大致如下:
{"name": "Your App Name","display_override": ["window-controls-overlay"],"short_name": "Short Name","orientation": "any","description": "App Description","start_url": "xxx.html","scope": "./","display": "fullscreen","background_color": "#000000","theme_color": "#000000","icons": [{"src": "icon-192x192.png","sizes": "192x192","type": "image/png"},{"src": "icon-256x256.png","sizes": "256x256","type": "image/png"},{"src": "icon-512x512.png","sizes": "512x512","type": "image/png"}],"screenshots": [{"src": "screenshot.jpg","sizes": "640x300","type": "image/jpg"}],"shortcuts": [{"name": "Purchase","url": "xxx.html","icons": [{ "src": "shortcuts.png", "sizes": "16x16" }]}],"protocol_handlers": [{"protocol": "web","url": "xxx.html#!/%s"}]
}
然后在html页面的head头部配置信息:
<link rel="manifest" href="/manifest.json" />
<meta name="theme-color" content="#000000" />
<meta name="mobile-web-app-capable" content="yes" />
<meta name="mobile-web-app-title" content="Your App Name" />
<link rel="apple-touch-icon" href="icon-192x192.png" />
接下来可以先参照MDN的官方教程:
https://developer.mozilla.org/en-US/docs/Web/API/Window/beforeinstallprompt_event
当浏览器检测到某个网站可以进行 installed as a Progressive Web App 时,将触发 beforeinstallprompt 事件。
第一步:先增加一个button按钮
<button id="install" hidden>Install</button>
第二步,用js监听事件
- 当浏览器检测到页面符合 PWA 安装条件时,会触发 beforeinstallprompt 事件。可以监听此事件并保存触发它的对象,以便在适当的时机调用。
- 然后在合适的业务逻辑中(例如点击安装按钮)调用 prompt() 显示安装弹窗。
- 通过清除 installPrompt 变量并再次隐藏自身来重置其状态。
let installPrompt = null;
const installButton = document.querySelector("#install");window.addEventListener("beforeinstallprompt", (event) => {event.preventDefault();installPrompt = event;installButton.removeAttribute("hidden");
});installButton.addEventListener("click", async () => {if (!installPrompt) {return;}const result = await installPrompt.prompt();console.log(`Install prompt was: ${result.outcome}`);installPrompt = null;installButton.setAttribute("hidden", "");
});
如果在VUE中使用,那么需要用以下方法
- 增加Vue的 created 生命周期函数,beforeinstallprompt 监听方法只能写在 created 内,mounted方法不管用。
- 提前设置变量接收监听事件返回对象,用来按钮点击时的操作
- 单独为按钮增加点击时的响应事件
created() {window.addEventListener("beforeinstallprompt", (event) => {event.preventDefault()// 提前设置一个变量接收监听对象this.installPrompt = event// 提前设置一个开关用来隐藏显示安装按钮this.isShowInstallButton = true})
}// 安装PWA应用
onInstallApp() {if (!this.installPrompt) {return}this.installPrompt.prompt().then(result => {this.disableInAppInstallPrompt();console.log(`Install prompt was: ${result.outcome}`);});
},
// 卸载事件隐藏安装按钮
disableInAppInstallPrompt() {this.installPrompt = null;this.isShowInstallButton = false
}
<button v-show="isShowInstallButton" @click="onInstallApp()">添加到桌面</button>
