Search Unity

Unity WebGL Firebase Cloud messaging jslib Plugin

Discussion in 'Web' started by StrayBlackFox, Feb 28, 2020.

  1. StrayBlackFox

    StrayBlackFox

    Joined:
    Nov 5, 2015
    Posts:
    7
    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
    Code (JavaScript):
    1.  
    2. <head>
    3.         <script src="https://www.gstatic.com/firebasejs/7.8.0/firebase-app.js"></script>
    4.         <script src="https://www.gstatic.com/firebasejs/7.8.0/firebase-messaging.js"></script>
    5.         // something else
    6. </head>
    7.  

    create WebGLPushNotifications.jslib plugin in Assets/Plugins/WebGL

    Code (JavaScript):
    1. var WebGLPushNotifications = {
    2.         SubscribeWebPush: function () {
    3.         try {
    4.              var firebaseConfig = {
    5.               //your config
    6.              };
    7.  
    8.              firebase.initializeApp(firebaseConfig);
    9.    
    10.              var messaging = firebase.messaging();
    11.    
    12.              messaging.usePublicVapidKey("--your public key--");
    13.    
    14.    
    15.              Notification.requestPermission().then(function(
    16.                  if (permission === 'granted') {
    17.                      messaging.getToken().then(function(currentToken) {
    18.                              if (currentToken) {
    19.                                  SendMessage('NotificationManager', 'OnWebNotificationToken', currentToken);
    20.                              } else {
    21.                                  console.log('No Instance ID token available. Request permission to generate one.');                  
    22.                              }
    23.                          }).catch(function(err) {
    24.                              console.log('An error occurred while retrieving token. ', err);
    25.                          });
    26.                  } else {
    27.                      console.log('Unable to get permission to notify.');
    28.                  }
    29.              });
    30.    
    31.  
    32.                
    33.                 messaging.onTokenRefresh(function(){
    34.                   messaging.getToken().then(function(refreshedToken) {
    35.                     SendMessage('NotificationManager', 'OnWebNotificationToken', refreshedToken);
    36.                   }).catch(function(err) {
    37.                     console.log('Unable to retrieve refreshed token ', err);
    38.                   });
    39.                 });
    40.             }
    41.             catch(e)
    42.             {
    43.                 console.log('Unable to retrieve refreshed token ', err);
    44.             }    
    45.         }    
    46.     };
    47. mergeInto(LibraryManager.library, WebGLPushNotifications);

    create c# Script WebNotifications.cs
    Code (CSharp):
    1. using System;
    2. using System.Collections;
    3. using System.Collections.Generic;
    4. using System.Collections.Specialized;
    5. using System.Runtime.InteropServices;
    6. using UnityEngine;
    7. using System.Linq;
    8. using System.Text;
    9.  
    10. public class WebNotifications : MonoBehaviour
    11. {
    12. #if UNITY_WEBGL
    13.  
    14.     [DllImport("__Internal")]
    15.     private static extern void SubscribeWebPush();
    16.  
    17.    
    18.  
    19.     public static WebNotifications Instance;
    20.     private static bool _initializeCalled = false;
    21.     private void Awake()
    22.     {
    23.         Instance = this;    
    24.     }
    25.  
    26.     // Init firebase after login
    27.     public void Init()
    28.     {
    29.         SubscribeWebPush();
    30.     }
    31.    
    32.  
    33.     public void OnWebNotificationToken(string token)
    34.     {
    35.         Debug.Log("Got token : " + token);
    36.         // send token to server  
    37.     }
    38.  
    39.     public void OnMessageGot(string data)
    40.     {
    41.         //got message
    42.     }
    43.  
    44. #endif
    45. }
    46.  

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

    Now add firebase-messaging-sw.js

    Code (CSharp):
    1.  
    2. importScripts('https://www.gstatic.com/firebasejs/7.8.0/firebase-app.js');
    3.  
    4. const firebaseConfig = {
    5. // Your config
    6. };
    7.  
    8. firebase.initializeApp(firebaseConfig);
    9.  
    10. self.addEventListener('push', function(e) {
    11.   var body;
    12.  
    13.   if (e.data) {
    14.     body = e.data.json();
    15.  
    16.     if(body && body.notification){
    17.       var mIcon = body.notification.icon ? body.notification.icon :  '';
    18.       var mTitle = body.notification.title ? body.notification.title : '';
    19.       var mBody =  body.notification.body ? body.notification.body : '';
    20.       var mLink = '';
    21.  
    22.       if(body.notification)
    23.         var options = {
    24.           body: mBody,
    25.           icon: mIcon,
    26.           data: {
    27.             url: mLink,
    28.             dateOfArrival: Date.now(),
    29.             primaryKey: 1
    30.           },
    31.         };
    32.         e.waitUntil(
    33.           clients.matchAll({includeUncontrolled: true, type: 'window'}).then(matchedClients => {
    34.             var oW = false;
    35.             for (let client of matchedClients) {
    36.                if (client.url.includes(mLink) && 'focused' in client && client.focused) {
    37.                   oW = true;
    38.                 }
    39.             }
    40.             if(!oW) return self.registration.showNotification(mTitle, options);
    41.           })
    42.         );
    43.     }
    44.   }
    45. });
    46.  
    47. self.addEventListener('notificationclick', event => {
    48.     const rootUrl = event.notification.data.url;
    49.     event.notification.close();
    50.     event.waitUntil(
    51.       clients.matchAll({includeUncontrolled: true, type: 'window'}).then(matchedClients => {
    52.         for (let client of matchedClients) {
    53.           console.log(client.url);
    54.     if (client.url.includes(rootUrl)) {
    55.             return client.focus();
    56.           }
    57.         }
    58.         return clients.openWindow(event.notification.data.lnk);
    59.       })
    60.     );
    61. });
    62.  
     
    Hangpt_bap likes this.
  2. intaj_cse

    intaj_cse

    Joined:
    Nov 25, 2014
    Posts:
    10
    Hi @StrayBlackFox , Thank you for this,
    I want to know where to add "firebase-messaging-sw.js"
    Need your help
     
  3. Marks4

    Marks4

    Joined:
    Feb 25, 2018
    Posts:
    547
    I just released an asset that enables you to use firebase on webgl. Cloud Messaging is included.