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.

Π’ Unity WebGL сСрвис-Π²ΠΎΡ€ΠΊΠ΅Ρ€ Π½Π΅ кладётся Π²Π½ΡƒΡ‚Ρ€ΡŒ Π±ΠΈΠ»Π΄ΠΎΠ² (Build/, TemplateData/), Π° рСгистрируСтся Π½Π° ΡƒΡ€ΠΎΠ²Π½Π΅ корня сайта ΠΈΠ»ΠΈ ΠΏΠΎΠ΄ΠΏΠ°ΠΏΠΊΠΈ, Π³Π΄Π΅ Π»Π΅ΠΆΠΈΡ‚ WebGL-Π±ΠΈΠ»Π΄. ΠŸΡ€ΠΈΡ‡ΠΈΠ½Π° Π² Ρ‚ΠΎΠΌ, Ρ‡Ρ‚ΠΎ сСрвис-Π²ΠΎΡ€ΠΊΠ΅Ρ€ ΠΏΠΎ спСцификации Β«Π²ΠΈΠ΄ΠΈΡ‚Β» Ρ‚ΠΎΠ»ΡŒΠΊΠΎ свой scope (ΠΏΠ°ΠΏΠΊΡƒ, Π³Π΄Π΅ Π»Π΅ΠΆΠΈΡ‚ Ρ„Π°ΠΉΠ», ΠΈ всС Π²Π»ΠΎΠΆΠ΅Π½Π½Ρ‹Π΅).

Как ΠΏΡ€Π°Π²ΠΈΠ»ΡŒΠ½ΠΎ Ρ€Π°Π·ΠΌΠ΅ΡΡ‚ΠΈΡ‚ΡŒ:

  1. ПолоТи Ρ‚Π²ΠΎΠΉ Ρ„Π°ΠΉΠ», Π½Π°ΠΏΡ€ΠΈΠΌΠ΅Ρ€ firebase-messaging-sw.js, рядом с index.html Unity-Π±ΠΈΠ»Π΄Π°, Ρ‚ΠΎ Π΅ΡΡ‚ΡŒ Π² Ρ‚Ρƒ ΠΆΠ΅ Π΄ΠΈΡ€Π΅ΠΊΡ‚ΠΎΡ€ΠΈΡŽ, ΠΊΡƒΠ΄Π° Ρ‚Ρ‹ Π²Ρ‹ΠΊΠ»Π°Π΄Ρ‹Π²Π°Π΅ΡˆΡŒ Build/, TemplateData/.
/webgl_build/
   index.html
   firebase-messaging-sw.js   <-- сюда
   Build/
   TemplateData/
  1. Π’ index.html (ΠΈΠ»ΠΈ ΠΎΡ‚Π΄Π΅Π»ΡŒΠ½ΠΎΠΌ скриптС, ΠΊΠΎΡ‚ΠΎΡ€Ρ‹ΠΉ загруТаСтся ΠΏΡ€ΠΈ стартС) зарСгистрируй сСрвис-Π²ΠΎΡ€ΠΊΠ΅Ρ€:
<script>
  if ('serviceWorker' in navigator) {
    navigator.serviceWorker.register('firebase-messaging-sw.js')
      .then(reg => {
        console.log('Service Worker registered with scope:', reg.scope);
      })
      .catch(err => {
        console.error('Service Worker registration failed:', err);
      });
  }
</script>
  1. Если Π±ΠΈΠ»Π΄ Unity Π»Π΅ΠΆΠΈΡ‚ Π½Π΅ Π² ΠΊΠΎΡ€Π½Π΅ Π΄ΠΎΠΌΠ΅Π½Π°, Π° Π½Π°ΠΏΡ€ΠΈΠΌΠ΅Ρ€ ΠΏΠΎ ΠΏΡƒΡ‚ΠΈ /game/, Ρ‚ΠΎ сСрвис-Π²ΠΎΡ€ΠΊΠ΅Ρ€ Ρ‚ΠΎΠΆΠ΅ Π΄ΠΎΠ»ΠΆΠ΅Π½ Π»Π΅ΠΆΠ°Ρ‚ΡŒ Π² /game/, ΠΈΠ½Π°Ρ‡Π΅ ΠΎΠ½ Π½Π΅ смоТСт ΠΏΠ΅Ρ€Π΅Ρ…Π²Π°Ρ‚Ρ‹Π²Π°Ρ‚ΡŒ push-увСдомлСния для ΠΈΠ³Ρ€Ρ‹.
https://example.com/game/index.html
https://example.com/game/firebase-messaging-sw.js

Π’ΠΎΠ³Π΄Π° Ρ€Π΅Π³ΠΈΡΡ‚Ρ€ΠΈΡ€ΠΎΠ²Π°Ρ‚ΡŒ Π½ΡƒΠΆΠ½ΠΎ Ρ‚Π°ΠΊ:

navigator.serviceWorker.register('/game/firebase-messaging-sw.js');

Π’Π°ΠΆΠ½ΠΎ:

  • Π€Π°ΠΉΠ» ΠΎΠ±ΡΠ·Π°Ρ‚Π΅Π»ΡŒΠ½ΠΎ Π΄ΠΎΠ»ΠΆΠ΅Π½ Π½Π°Ρ…ΠΎΠ΄ΠΈΡ‚ΡŒΡΡ Π½Π° Ρ‚ΠΎΠΌ ΠΆΠ΅ Π΄ΠΎΠΌΠ΅Π½Π΅ (ΠΈΠ»ΠΈ ΠΏΠΎΠ΄Π΄ΠΎΠΌΠ΅Π½Π΅) ΠΈΠ·-Π·Π° ΠΎΠ³Ρ€Π°Π½ΠΈΡ‡Π΅Π½ΠΈΠΉ бСзопасности.
  • Firebase Messaging ΠΆΠ΄Ρ‘Ρ‚, Ρ‡Ρ‚ΠΎ сСрвис-Π²ΠΎΡ€ΠΊΠ΅Ρ€ Π±ΡƒΠ΄Π΅Ρ‚ ΠΈΠΌΠ΅Π½Π½ΠΎ Π² ΠΊΠΎΡ€Π½Π΅ ΠΏΡ€ΠΎΠ΅ΠΊΡ‚Π°, Π³Π΄Π΅ загруТаСтся WebGL.

Integrating Firebase Cloud Messaging (FCM) into a Unity WebGL build requires the use of a .jslib plugin to bridge the gap between Unity’s C# code and the browser’s JavaScript environment, where the Firebase JavaScript SDK operates.