Introduction

Appgain.io Web SDK is the way you can use Appgain Web Push to send Push Notifications to your website visitors

Installation

Appgain web push notifications is integrated by default in our mobile landing pages and smart deep links, however you can add it also to your website by following below steps :

  • Download firebase-messaging-sw.js and firebase.js
  • Add firebase-messaging-sw.js and firebase.js to root of website

  • Enable https on your website

  • add onload="requestPermission()" to body tag of your website

  • add below code to your home page, note to replace [Appgain Project Id] and [your website url]
< script src="https://www.gstatic.com/firebasejs/3.7.3/firebase.js" />
<script type="text/javascript">
    var config = {

        "api": {
            "notification_status": "https://notify.appgain.io/[Appgain Project Id]/recordstatus",
            "subscribe": "https://notify.appgain.io/[Appgain Project Id]/webPushSubscribe",
            "unsubscribe": "https://notify.appgain.io/[Appgain Project Id]/webPushUnSubscribe"
        },
        "channel": {
            "type": "website",
            "url": "[your website url]"
        },
        "firebase": {
            "apiKey": "AIzaSyA4Nw7F9s5tFB-NvcW85Z0R6RQQbwn56JI",
            "messagingSenderId": "527722014525"
        }
    };
    // Initialize Firebase
    firebase.initializeApp(config.firebase);
    // Messaging Object
    const messaging = firebase.messaging();
    if ('serviceWorker' in navigator) {
        navigator.serviceWorker.register('/firebase-messaging-sw.js')
            .then(function(reg) {
                // registration worked
                messaging.useServiceWorker(reg)
                console.log('Registration succeeded. Scope is ' + reg);
            }).catch(function(error) {
                // registration failed
                console.log('Registration failed with ' + error);
            });
    }
    // On Token Refresh
    messaging.onTokenRefresh(function() {
        messaging.getToken()
            .then(function(refreshedToken) {
                console.log('Token refreshed.');
                setTokenSentToServer(false);
                sendTokenToServer(refreshedToken);
            })
            .catch(function(err) {
                console.log('Unable to retrieve refreshed token ', err);
                showToken('Unable to retrieve refreshed token ', err);
            });
    });
    // On Message
    messaging.onMessage(function(payload) {
        console.log("Message received. ", payload)
        if (config.api.hasOwnProperty("userId")) {
            fetch(config.api.notification_status, {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                    "Accept": "application/json"
                },
                body: JSON.stringify({
                    channel: config.channel,
                    action: {
                        name: received,
                        value: 1564
                    },
                    userId: config.api.userId,
                    campaign_id: payload.notification.campaign_id
                })
            });
        }
    })
    function showToken(currentToken) {
        console.log('showToken : ', currentToken);
    }
    function sendTokenToServer(currentToken) {
        if (!isTokenSentToServer()) {
            console.log('Sending token to server...');
            showToken(currentToken);
            var query = "";
            if (config.api.hasOwnProperty("userId")) {
                query = "?userId=" + config.api.userId
            }
            fetch(config.api.subscribe + query, {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                    "Accept": "application/json"
                },
                body: JSON.stringify({
                    channel: config.channel,
                    subscription: currentToken
                })
            });
            setTokenSentToServer(true);
        } else {
            console.log('Token already sent to server so won\'t send it again ' +
                'unless it changes');
        }
    }
    function isTokenSentToServer() {
        if (window.localStorage.getItem('sentToServer') == 1) {
            return true;
        }
        return false;
    }
    function setTokenSentToServer(sent) {
        window.localStorage.setItem('sentToServer', sent ? 1 : 0);
    }
    // Subscribe
    function requestPermission() {
        console.log('Requesting permission...');
        messaging.requestPermission()
            .then(function() {
                console.log('Notification permission granted.');
                messaging.getToken().then(function(token) {
                    sendTokenToServer(token);
                });
            })
            .catch(function(err) {
                console.log('Unable to get permission to notify.', err);
            });
    }
    // Unsubscribe
    function deleteToken() {
        messaging.getToken()
            .then(function(currentToken) {
                console.log('showToken  to be deleted : ', currentToken)
                messaging.deleteToken(currentToken)
                    .then(function() {
                        console.log('Token deleted.');
                        fetch(config.api.unsubscribe, {
                            method: "PUT",
                            headers: {
                                "Content-Type": "application/json",
                                "Accept": "application/json"
                            },
                            body: JSON.stringify({
                                subscription: currentToken
                            })
                        });
                        setTokenSentToServer(false);
                    })
                    .catch(function(err) {
                        console.log('Unable to delete token. ', err);
                    });
            })
            .catch(function(err) {
                console.log('Error retrieving Instance ID token. ', err);
                showToken('Error retrieving Instance ID token. ', err);
            });
    }
</script>