我仅仅通过创建一个主题组件添加了该按钮。
只需创建一个新的主题组件。
在 header 中添加以下 JS 代码:
<script>
let deferredPrompt; // 允许显示安装提示
const installButton = document.getElementById("install_button");
window.addEventListener("beforeinstallprompt", e => {
console.log("beforeinstallprompt 事件已触发");
// 阻止 Chrome 76 及更早版本自动显示提示
e.preventDefault();
// 暂存事件以便稍后触发
deferredPrompt = e;
// 显示安装按钮
installButton.hidden = false;
installButton.addEventListener("click", installApp);
});
function installApp() {
// 显示提示
deferredPrompt.prompt();
installButton.disabled = true;
// 等待用户响应提示
deferredPrompt.userChoice.then(choiceResult => {
if (choiceResult.outcome === "accepted") {
console.log("PWA 设置已接受");
installButton.hidden = true;
} else {
console.log("PWA 设置已拒绝");
}
installButton.disabled = false;
deferredPrompt = null;
});
}
window.addEventListener("appinstalled", evt => {
console.log("appinstalled 事件已触发", evt);
});
</script>
并在需要安装按钮的位置放置以下 HTML:
<button id="install_button" hidden>安装</button>
该按钮默认隐藏,仅在 PWA 未安装时显示。
我已在 Chrome 上对此进行了测试。