<!----------------------HTML开始------------------------>
<head>
<link rel="manifest" href="/static/admin/pwa/manifest.json">
</head>
<body>
<a href="javascript:;" class="tk weChatCode add-desktop-button">
<i class="icon-adv icon-desktop"></i>
<p class="downa">桌面端</p>
<div class="downbox click-desktop">
<p class="ap">添加到桌面</p>
<img src="/static/admin/pwa/desktop.png" style="width: 100px;height: auto" alt="" class="erwei">
</div>
</a>
</body>
<!----------------------HTML结束------------------------>
<!----------------------JS开始------------------------>
// 检测浏览器是否支持SW
if(navigator.serviceWorker != null){
navigator.serviceWorker.register('/admin.php/union/unionSys/sw')
.then(res => {// console.log('注册成功') })
.catch(error => { // console.log('注册失败') })
}else{
// console.log('不支持sw')
}
let deferredPrompt;
const addBtn = document.querySelector('.add-desktop-button');
addBtn.style.display = 'none';
window.addEventListener('beforeinstallprompt', (e) => {
// console.log('beforeinstallprompt')
// Prevent Chrome 67 and earlier from automatically showing the prompt
e.preventDefault();
// Stash the event so it can be triggered later.
deferredPrompt = e;
// Update UI to notify the user they can add to home screen
showInstallPromotion()
});
function showInstallPromotion(){
addBtn.style.display = 'block';
const clickBtn = document.querySelector('.click-desktop');
clickBtn.addEventListener('click', (e) => {
// hide our user interface that shows our A2HS button
addBtn.style.display = 'none';
// 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');
} else {
// console.log('User dismissed the A2HS prompt');
}
deferredPrompt = null;
});
});
}
function hideInstallPromotion(){
layer.msg('安装成功')
}
window.addEventListener('appinstalled', () => {
// Hide the app-provided install promotion
hideInstallPromotion();
// Clear the deferredPrompt so it can be garbage collected
deferredPrompt = null;
// Optionally, send analytics event to indicate successful install
// console.log('PWA was installed');
});
<!----------------------JS结束------------------------>