0

当PWA 应用程序请求用户权限(如地理位置和通知)时,添加到主屏幕的安装横幅不会显示在适用于 android 的 chrome 浏览器上

我也尝试使用beforeinstallprompt事件来实现这个功能,但它没有被触发

服务工作者.js

  self.importScripts('/js/push-notification/push-notifications-controller.js');
(function () {
    'use strict';
    const pushNotificationTitle = 'FM Service';
    // Update 'version' if you need to refresh the cache
    var version = '~1.0.0.1129^';
    var offlineUrl = "/offline.html";

    // Store core files in a cache (including a page to display when offline)
    function updateStaticCache() {
        return caches.open(version)
            .then(function (cache) {
                return cache.addAll([
                    offlineUrl,

                ]);
            });
    }

    function addToCache(request, response) {
        if (!response.ok && response.type !== 'opaque')
            return;

        var copy = response.clone();
        caches.open(version)
            .then(function (cache) {


                cache.put(request, copy);
            });
    }

    function serveOfflineImage(request) {
        if (request.headers.get('Accept').indexOf('image') !== -1) {
            return new Response('<svg role="img" aria-labelledby="offline-title" viewBox="0 0 400 300" xmlns="http://www.w3.org/2000/svg"><title id="offline-title">Offline</title><g fill="none" fill-rule="evenodd"><path fill="#D8D8D8" d="M0 0h400v300H0z"/><text fill="#9B9B9B" font-family="Helvetica Neue,Arial,Helvetica,sans-serif" font-size="72" font-weight="bold"><tspan x="93" y="172">offline</tspan></text></g></svg>', { headers: { 'Content-Type': 'image/svg+xml' } });
        }
    }

    self.addEventListener('install', function (event) {
        event.waitUntil(updateStaticCache());
        self.skipWaiting();
    });

    self.addEventListener('activate', function (event) {
        event.waitUntil(
            caches.keys()
                .then(function (keys) {
                    // Remove caches whose name is no longer valid
                    return Promise.all(keys
                        .filter(function (key) {
                            return key.indexOf(version) !== 0;
                        })
                        .map(function (key) {
                            return caches.delete(key);
                        })
                    );
                })
        );
    });

    self.addEventListener('message', function (event) {

        if (event.data.action === 'skipWaiting') {
            self.skipWaiting();
        }
    });

    self.addEventListener('fetch', function (event) {
        var request = event.request;

        // Always fetch non-GET requests from the network
        if (request.method !== 'GET' || request.url.match(/\/browserLink/ig)) {
            event.respondWith(
                fetch(request)
                    .catch(function () {
                        return caches.match(offlineUrl);
                    })
            );
            return;
        }

        // For HTML requests, try the network first, fall back to the cache, finally the offline page
        if (request.headers.get('Accept').indexOf('text/html') !== -1) {
            event.respondWith(
                fetch(request)
                    .then(function (response) {
                        // Stash a copy of this page in the cache
                        addToCache(request, response);
                        return response;
                    })
                    .catch(function () {
                        return caches.match(request)
                            .then(function (response) {
                                return response || caches.match(offlineUrl);
                            });
                    })
            );
            return;
        }

        // cache first for fingerprinted resources
        if (request.url.match(/(\?|&)v=/ig)) {
            event.respondWith(
                caches.match(request)
                    .then(function (response) {
                        return response || fetch(request)
                            .then(function (response) {
                                addToCache(request, response);
                                return response || serveOfflineImage(request);
                            })
                            .catch(function () {
                                return serveOfflineImage(request);
                            });
                    })
            );

            return;
        }

        // network first for non-fingerprinted resources
        event.respondWith(
            fetch(request)
                .then(function (response) {
                    // Stash a copy of this page in the cache
                    addToCache(request, response);
                    return response;
                })
                .catch(function () {
                    return caches.match(request)
                        .then(function (response) {
                            return response || serveOfflineImage(request);
                        })
                        .catch(function () {
                            return serveOfflineImage(request);
                        });
                })
        );
    });

    //push notification events

    self.addEventListener('push', function (event) {
        event.waitUntil(self.registration.showNotification(pushNotificationTitle, {
            body: event.data.text(),
            icon: '/img/fm-badge-192x192.png'
        }));
    });

    self.addEventListener('notificationclick', function (event) {
        console.log('[Service Worker] Notification click Received.');

        event.notification.close();
    });

    self.addEventListener('pushsubscriptionchange', function (event) {
        const handlePushSubscriptionChangePromise = Promise.resolve();

        if (event.oldSubscription) {
            handlePushSubscriptionChangePromise = handlePushSubscriptionChangePromise.then(function () {
                return PushNotificationsController.discardPushSubscription(event.oldSubscription);
            });
        }

        if (event.newSubscription) {
            handlePushSubscriptionChangePromise = handlePushSubscriptionChangePromise.then(function () {
                return PushNotificationsController.storePushSubscription(event.newSubscription);
            });
        }

        if (!event.newSubscription) {
            handlePushSubscriptionChangePromise = handlePushSubscriptionChangePromise.then(function () {
                return PushNotificationsController.retrievePublicKey().then(function (applicationServerPublicKey) {
                    return pushServiceWorkerRegistration.pushManager.subscribe({
                        userVisibleOnly: true,
                        applicationServerKey: applicationServerPublicKey
                    }).then(function (pushSubscription) {
                        return PushNotificationsController.storePushSubscription(pushSubscription);
                    });
                });
            });
        }

        event.waitUntil(handlePushSubscriptionChangePromise);
    });

    self.addEventListener('notificationclick', function (event) {
        event.notification.close();
    });
    // end push notification events
})();

索引.html

<script nws-csp-add-nonce="true">
         let newWorker;
        // The click event on the pop up notification
        document.getElementById('reload').addEventListener('click', function () {
            localStorage.setItem("IsNewVersionAvailable", false);
            window.location.reload();
        });

        'serviceWorker' in navigator && navigator.serviceWorker.register('/serviceworker.js').then(reg => {

            pushServiceWorkerRegistration = reg;
            initializeUIState();

            writeToConsole('Push Service Worker has been registered successfully');
            subscribeForPushNotifications();
            writeToConsole('Subscribe Notification Successfully');

            reg.installing; // the installing worker, or undefined
            reg.waiting; // the waiting worker, or undefined
            reg.active; // the active worker, or undefined

            reg.addEventListener('updatefound', () => {
                // A wild service worker has appeared in reg.installing!
                newWorker = reg.installing;
                newWorker.state;
                // "installing" - the install event has fired, but not yet complete
                // "installed"  - install complete
                // "activating" - the activate event has fired, but not yet complete
                // "activated"  - fully active
                // "redundant"  - discarded. Either failed install, or it's been
                //                replaced by a newer version

                newWorker.addEventListener('statechange', () => {
                    switch (newWorker.state) {
                        case 'installed':

                            // There is a new service worker available, show the notification
                            if (navigator.serviceWorker.controller) {
                                localStorage.setItem("IsNewVersionAvailable", true);
                                $('#msg-newversion').removeClass('d-none');
                            }
                            break;
                    }
                });
            });
        });

        var refreshing;
        navigator.serviceWorker.addEventListener('controllerchange', () => {

            if (refreshing) return;
            window.location.reload();
            refreshing = true;
        });
    </script>

你们能告诉我你对此的反馈吗

感谢 Sahadev Dodiya

4

0 回答 0