首页 > 解决方案 > 自定义“添加到主屏幕”横幅。在安培

问题描述

我目前正在处理自定义“添加到主屏幕”的任务。我们的网站是 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它不适用它的代码。该按钮仍然出现在前端,但它不起作用。在移动设备上,它仍然是默认横幅出现。

标签: javascriptservice-workeramp-htmlprogressive-web-appshomescreen

解决方案


推荐阅读