Unity WebGL Firebase Cloud messaging jslib Plugin

Hi everyone, i spent a lot of time to make friends webgl and firebase cloud messaging, and may be save someone else time. Here short instruction:

add this code to index page

<head>
        <script src="https://www.gstatic.com/firebasejs/7.8.0/firebase-app.js"></script>
        <script src="https://www.gstatic.com/firebasejs/7.8.0/firebase-messaging.js"></script>
        // something else
</head>

create WebGLPushNotifications.jslib plugin in Assets/Plugins/WebGL

var WebGLPushNotifications = {
        SubscribeWebPush: function () {
        try {
             var firebaseConfig = {
              //your config
             };

             firebase.initializeApp(firebaseConfig);

             var messaging = firebase.messaging();

             messaging.usePublicVapidKey("--your public key--");


             Notification.requestPermission().then(function(
                 if (permission === 'granted') {
                     messaging.getToken().then(function(currentToken) {
                             if (currentToken) {
                                 SendMessage('NotificationManager', 'OnWebNotificationToken', currentToken);
                             } else {
                                 console.log('No Instance ID token available. Request permission to generate one.');                  
                             }
                         }).catch(function(err) {
                             console.log('An error occurred while retrieving token. ', err);
                         });
                 } else {
                     console.log('Unable to get permission to notify.');
                 }
             });



                messaging.onTokenRefresh(function(){
                  messaging.getToken().then(function(refreshedToken) {
                    SendMessage('NotificationManager', 'OnWebNotificationToken', refreshedToken);
                  }).catch(function(err) {
                    console.log('Unable to retrieve refreshed token ', err);
                  });
                });
            }
            catch(e)
            {
                console.log('Unable to retrieve refreshed token ', err);
            }     
        }    
    };
mergeInto(LibraryManager.library, WebGLPushNotifications);

create c# Script WebNotifications.cs

using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Runtime.InteropServices;
using UnityEngine;
using System.Linq;
using System.Text;

public class WebNotifications : MonoBehaviour
{
#if UNITY_WEBGL

    [DllImport("__Internal")]
    private static extern void SubscribeWebPush();



    public static WebNotifications Instance;
    private static bool _initializeCalled = false;
    private void Awake()
    {
        Instance = this;    
    }

    // Init firebase after login
    public void Init()
    {
        SubscribeWebPush();
    }


    public void OnWebNotificationToken(string token)
    {
        Debug.Log("Got token : " + token);
        // send token to server   
    }

    public void OnMessageGot(string data)
    {
        //got message
    }

#endif
}

Then Create gameobject NotificationManager, and add component WebNotifications to it.

Now add firebase-messaging-sw.js

importScripts('https://www.gstatic.com/firebasejs/7.8.0/firebase-app.js');

const firebaseConfig = {
// Your config
};

firebase.initializeApp(firebaseConfig);

self.addEventListener('push', function(e) {
  var body;

  if (e.data) {
    body = e.data.json();

    if(body && body.notification){
      var mIcon = body.notification.icon ? body.notification.icon :  '';
      var mTitle = body.notification.title ? body.notification.title : '';
      var mBody =  body.notification.body ? body.notification.body : '';
      var mLink = '';

      if(body.notification)
        var options = {
          body: mBody,
          icon: mIcon,
          data: {
            url: mLink,
            dateOfArrival: Date.now(),
            primaryKey: 1
          },
        };
        e.waitUntil(
          clients.matchAll({includeUncontrolled: true, type: 'window'}).then(matchedClients => {
            var oW = false;
            for (let client of matchedClients) {
               if (client.url.includes(mLink) && 'focused' in client && client.focused) {
                  oW = true;
                }
            }
            if(!oW) return self.registration.showNotification(mTitle, options);
          })
        );
    }
  }
});

self.addEventListener('notificationclick', event => {
    const rootUrl = event.notification.data.url;
    event.notification.close();
    event.waitUntil(
      clients.matchAll({includeUncontrolled: true, type: 'window'}).then(matchedClients => {
        for (let client of matchedClients) {
          console.log(client.url);
    if (client.url.includes(rootUrl)) {
            return client.focus();
          }
        }
        return clients.openWindow(event.notification.data.lnk);
      })
    );
});
1 Like

Hi @StrayBlackFox , Thank you for this,
I want to know where to add "firebase-messaging-sw.js"
Need your help

I just released an asset that enables you to use firebase on webgl. Cloud Messaging is included.