javascript - 自定义“添加到主屏幕”横幅。在安培
问题描述
我目前正在处理自定义“添加到主屏幕”的任务。我们的网站是 AMP,我正在使用工作人员服务和清单 = PWA。
我已经添加了 AMP 库,这就是我安装工作服务的方式。
放大器部分。
<amp-install-serviceworker
src="/sw.js"
data-iframe-src="/pwa/sw.html"
layout="nodisplay">
</amp-install-serviceworker>
<button class="add-button"> add to homescreen </button>
sw.js
self.addEventListener('install', function (e) {
e.waitUntil(
caches.open('iprice-coupons').then(function (cache) {
return cache.addAll([]);
})
);
});
self.addEventListener('fetch', function (event) {
event.respondWith(fetch(event.request));
// or simply don't call event.respondWith, which
// will result in default browser behaviour
});
sw.html
<!DOCTYPE html>
<html>
<head>
<title>installing service worker</title>
<script type="text/javascript">
if('serviceWorker' in navigator) {
navigator.serviceWorker
.register('/sw.js')
.then(function() { console.log('Service Worker
Registered'); });
}
// Code to handle install prompt on desktop
let deferredPrompt;
const addBtn = document.querySelector('.add-button');
addBtn.style.display = 'none';
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;
// Update UI to notify the user they can add to home screen
addBtn.style.display = 'block';
addBtn.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;
});
});
});
</script>
</head>
<body>
</body>
</html>
不知何故,sw.html
它不适用它的代码。该按钮仍然出现在前端,但它不起作用。在移动设备上,它仍然是默认横幅出现。
解决方案
推荐阅读
- javascript - 不保留显示每个键的字母(纯javascript)
- neo4j - 如何使这个查询在 neo4j 中更高效?
- javascript - Google Maps Javascript API - 图例最大高度
- json.net - Json.NET Schema 我可以在我的模式中发出非标准属性吗?
- android - Android Management API 策略信息亭模式 - 维护时段内未应用系统更新
- html - 如何将活动类设置为从 icomoon 生成的 Web 字体图标
- python - Sklearn 使用带有数字数据的自然语言处理
- python - 使用 requests/selenium/pywinauto 上传图片
- bash - bash 命令在文本文件的一行中查找特定的信息?
- php - Laravel 集合发出 SQL 查询