繁体   English   中英

Web-Push通知脚本适用于Firefox但不适用于Chrome

[英]Web-Push notification script working on Firefox but not on Chrome

我正在构建一个Web推送通知系统,我正在使用此示例中使用的概念:

https://github.com/Minishlink/web-push-php-example

我的JS文件中有以下代码。 它检查API支持,检查是否未禁用通知,注册服务工作者,请求显示通知的权限,如果允许则订阅用户并将详细信息发送到服务器。 如果用户已订阅,则更新DB中的端点值。

当我在Firefox 61上运行它时,它工作正常,但当我在Chrome 67上运行它时,我收到此错误:

Uncaught (in promise) TypeError: Cannot read property 'getKey' of null
    at pushSubscribe (notification.js:48)
    at navigator.serviceWorker.ready.then.then.subscription (notification.js:30)

我的理解是,当服务工作者注册并且用户被订阅时,Chrome不会检测到订阅 ,因此它会给出错误。 任何想法如何解决这一问题?

谢谢。

document.addEventListener('DOMContentLoaded', () => {
    // Feature detection
    if (!('serviceWorker' in navigator)) {
        alert('Service Worker API isn’t supported.');
    } else if (!('PushManager' in window)) {
        alert('Push API isn’t supported.');
    } else if (!('Notification' in window)) {
        alert('Notifications API isn’t supported.');
    } else if (!('showNotification' in ServiceWorkerRegistration.prototype)) {
        alert('Notifications aren’t supported.');

    // Check permission
    } else if (Notification.permission == 'denied') {
        alert('Notifications are disabled.');
    } else {

        // Register service worker
        navigator.serviceWorker.register('/service-worker.js').then(() => {
            navigator.serviceWorker.ready.then(serviceWorkerRegistration => serviceWorkerRegistration.pushManager.getSubscription()).then(subscription => {
                if (!subscription) {
                    // Subscribe user
                    navigator.serviceWorker.ready.then(serviceWorkerRegistration => serviceWorkerRegistration.pushManager.subscribe({
                        userVisibleOnly: true,
                        applicationServerKey: urlBase64ToUint8Array('BNwjaNBKGM13IAef-gJr7C95W3yLJe2F5X0zLnwacN3zCnZK15Vqf3ijeHl9k7K0yBFX3ZwxAmldPoVDpi6iETA'),
                    })).then(subscription => {
                        return pushSubscribe(subscription);
                    });
                }
                // Update endpoint
                return pushSubscribe(subscription);
            });
        });

        function urlBase64ToUint8Array(base64String) {
            const padding = '='.repeat((4 - base64String.length % 4) % 4);
            const base64 = (base64String + padding).replace(/\-/g, '+').replace(/_/g, '/');

            const rawData = window.atob(base64);
            const outputArray = new Uint8Array(rawData.length);

            for (let i = 0; i < rawData.length; ++i) {
                outputArray[i] = rawData.charCodeAt(i);
            }
            return outputArray;
        }

        function pushSubscribe(subscription) {
            const key = subscription.getKey('p256dh');
            const token = subscription.getKey('auth');
            const contentEncoding = (PushManager.supportedContentEncodings || ['aesgcm'])[0];

            return fetch('/scripts/notification-subscribe.php', {
                method: 'POST',
                body: JSON.stringify({
                    endpoint: subscription.endpoint,
                    publicKey: key ? btoa(String.fromCharCode.apply(null, new Uint8Array(key))) : null,
                    authToken: token ? btoa(String.fromCharCode.apply(null, new Uint8Array(token))) : null,
                    contentEncoding,
                    user: userId, // generated beforehand
                }),
            }).then(() => subscription);
        }
    }
});
        if(subscription){
const key = subscription.getKey('p256dh');
            const token = subscription.getKey('auth');
            const contentEncoding = (PushManager.supportedContentEncodings || ['aesgcm'])[0];

            return fetch('/scripts/notification-subscribe.php', {
                method: 'POST',
                body: JSON.stringify({
                    endpoint: subscription.endpoint,
                    publicKey: key ? btoa(String.fromCharCode.apply(null, new Uint8Array(key))) : null,
                    authToken: token ? btoa(String.fromCharCode.apply(null, new Uint8Array(token))) : null,
                    contentEncoding,
                    user: 1,
                }),
            }).then(() => subscription);
        }
}

Just modify this function hope pushSubscription with if block it works

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM