自定义“添加到主屏幕”横幅。在AMP中

时间:2018-11-24 06:47:39

标签: javascript service-worker amp-html progressive-web-apps homescreen

我目前正在处理自定义“添加到主屏幕”的任务。 我们的网站是AMP,我正在使用工作人员服务,清单= PWA。

我已经添加了AMP库,这就是我安装工作程序服务的方式。

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不适用它的代码。该按钮仍显示在前端,但不起作用。在移动设备上,它仍然是默认横幅。

0 个答案:

没有答案