首页 > 解决方案 > 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');
  }
}

标签: iosprogressive-web-apps

解决方案


推荐阅读