Firebase web push notification in ES5

2019-08-20 02:15发布

问题:

I am using FCM web JS SDK.

It is working fine in ES6 syntax. It uses lots of promises. I need to give support for ES5.I can not use promises.

Here is my current JS:

 // Initialize Firebase
    var config = {
        apiKey: 'xxx',
        authDomain: 'xxxx',
        databaseURL: 'xxxx',
        projectId: 'xxxx',
        storageBucket: 'xxxx',
        messagingSenderId: 'xxxx'
    };

    if (!firebase.apps.length) {
        firebase.initializeApp(config);
    }

    var vapidPublicKey = 'xxxx';
    var convertedVapidKey = urlBase64ToUint8Array(vapidPublicKey);
    var messaging = firebase.messaging();
    messaging.usePublicVapidKey('xxxx'); 

    // Register service worker

    if ('serviceWorker' in navigator) {

        var worker_url = serviceWorker.js + '&messagingSenderId=' + 12322;
        navigator.serviceWorker.register(worker_url).then(function (registration) {

            // Use this service worker
            messaging.useServiceWorker(registration);

            // Request permission
            messaging.requestPermission().then(function () {

                messaging.getToken().then(function (currentToken) {

                    if (currentToken) {
                        sendTokenToServer(currentToken);
                    }
                }).catch(function (err) {
                    console.error('An error occurred while retrieving token. ', err);
                });
            }).catch(function (err) {
                console.error('Unable to get permission to notify.', err);
            }); // Subscribe user

            registration.pushManager.subscribe({
                userVisibleOnly: true,
                applicationServerKey: convertedVapidKey
            }).catch(function (e) {
                console.error('Subcription error:', e);
            }); // Show notification on browser

            messaging.onMessage(function (payload) {
                displayNotification(payload);
            });
        }).catch(function (err) {
            // registration failed :(
            console.error('ServiceWorker registration failed: ', err);
        });

        /**
         * Callback fired if Instance ID token is updated.
         */
        messaging.onTokenRefresh(function () {
            messaging.getToken().then(function (refreshedToken) {
                // Indicate that the new Instance ID token has not yet been sent to the
                // app server.
                // Send Instance ID token to app server.
                sendTokenToServer(refreshedToken);
            }).catch(function (err) {
                console.log('Unable to retrieve refreshed token ', err);
            });
        });
    }

Now I need to implement this in ES5 syntax. Any help appreciated.