ios - PWA IOS Safari ServiceWorker 未启用
问题描述
嗨,我一直在尝试创建 PWA,它在 ANDROID 上运行良好,但在 iOS 中无法运行。我拥有所有正确的功能,但后来我发现Safari 不支持BeforeInstallPromptEvent ......所以我确保在 Safari 上没有运行该功能......但它仍然不起作用。我还需要做些什么才能让 PWA 在 Safari 中工作。我认为问题在于服务人员注册。
sw.js
var cacheName = 'cachecard';
var filesToCache = [
'./',
'./index.html',
'./css/style.css',
'./js/main.js'
];
/* Start the service worker and cache all of the app's content */
self.addEventListener('install', function(e) {
e.waitUntil(
caches.open(cacheName).then(function(cache) {
return cache.addAll(filesToCache);
})
);
self.skipWaiting();
});
/* Serve cached content when offline */
self.addEventListener('fetch', function(e) {
e.respondWith(
caches.match(e.request).then(function(response) {
return response || fetch(e.request);
})
);
});
索引.html
<div id="installContainer" class="hidden" >
<button id="butInstall" type="button">
*INSTALL APP*
</button>
</div>
<script src="js/main.js"></script>
<script>
// Initialize deferredPrompt for use later to show browser install prompt.
let deferredPrompt;
const divInstall = document.getElementById('installContainer');
const butInstall = document.getElementById('butInstall');
if ( !(varUA.indexOf("iphone") > -1 || varUA.indexOf("ipod") > -1) ) {
window.addEventListener('beforeinstallprompt', (event) => {
console.log('', 'beforeinstallprompt', event);
// Stash the event so it can be triggered later.
window.deferredPrompt = event;
// Remove the 'hidden' class from the install button container
divInstall.classList.toggle('hidden', false);
});
}
butInstall.addEventListener('click', async () => {
console.log('', 'butInstall-clicked');
const promptEvent = window.deferredPrompt;
if (!promptEvent) {
// The deferred prompt isn't available.
return;
}
// Show the install prompt.
promptEvent.prompt();
// Log the result
const result = await promptEvent.userChoice;
console.log('', 'userChoice', result);
// Reset the deferred prompt variable, since
// prompt() can only be called once.
window.deferredPrompt = null;
// Hide the install button.
divInstall.classList.toggle('hidden', true);
count=0;
});
window.addEventListener('appinstalled', (event) => {
console.log('', 'appinstalled', event);
// Clear the deferredPrompt so it can be garbage collected
window.deferredPrompt = null;
});
</script>
main.js
window.onload = () => {
// 'use strict';
console.log(navigator);
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('./sw.js');
}
}
解决方案
推荐阅读
- python - 创建类时有没有办法再次计算类变量?
- javascript - Vue this.$http.delete() 仅返回 500 内部服务器
- html - CSS Precedence Oddity - “#id tag” > “#tagId” 为什么?
- python - 如何使用 os 将文件保存到新文件夹?
- rust - 如何调用具有泛型类型的结构的关联函数?
- php - 检查是否在 Symfony 表达式语言注释中设置了用户对象
- javascript - 在不更改其原始值的情况下取回对象值 - Angular
- django - 如何从 makemigrations 命令添加另一个 0000n_initial.py 文件
- jquery - 从 OnGet 操作方法返回值返回剃须刀页面
- xcode - 如何使用 SwiftUI 显示 Game Center 排行榜