#webpush #FCM #integration #firebase.messaging
After a bit of experimentation I have integrated FCM and able to send web push notifications to WIX client.
Note: This does not require access to WIX root directory
Here is my take on the steps involved. Good luck.
1) Setup firebase project:
Setup is pretty straight forward, setup and configuration documentation available here ->
This step is required to continue with the remaining steps
2) WIX Client
Integration of Firebase SDK:
The SDK snippet is available from your firebase console
Add the Firebase SDK snippet into Wix by using settings -> add custom code
In addition to the SDK provided by Firebase the following updates are needed:
registration of custom service worker ( Required because WIX doesn’t allow access to root directory, see below )
To pass parameters between page and custom code snippet
From the page to custom code: wixWindow.postMessage(dataObj) and window.addEventListener
From custom code back to page: window.location.assign
eg:- window.location.assign(https://www.yoursite.com/?parametername=”value”)
Use wixLocation.query in the page to access parametername
Here is my sample custom code :
<!-- The core Firebase JS SDK is always required and must be listed first --> <script src="https://www.gstatic.com/firebasejs/8.3.2/firebase-app.js"</script>> <!-- TODO: Add SDKs for Firebase products that you want to use Add Firebase to your JavaScript project --> <script src="https://www.gstatic.com/firebasejs/8.3.2/firebase-analytics.js"</script>> <script src="https://www.gstatic.com/firebasejs/8.3.2/firebase-messaging.js"</script>> <script> const firebaseConfig = { apiKey: "**************************",
authDomain: "***************firebaseapp.com",
projectId: "************",
storageBucket: "*********.appspot.com",
messagingSenderId: "##########",
appId: "#######################",
measurementId: "###############" }; firebase.initializeApp(firebaseConfig);
firebase.analytics();
console.log("firebase ", firebase);
const messaging = firebase.messaging();
window.addEventListener('message', function(event) {
console.log("Data received :",event.data);
if( event.data !== null){ // perform this step only if page explicitly called with parameters
if('serviceWorker' in navigator){ // browser supports service workers
navigator.serviceWorker.register('_functions/firebase_messaging_sw_js').then((sw_registration) => {
messaging.requestPermission().then(()=>{
console.log("Permission granted");
messaging.getToken({serviceWorkerRegistration: sw_registration}).then((token)=>{
window.location.assign('https://www.wring.online/?fcm_token='+token);
}).catch((tokenError)=>{
//window.location.assign('https://www.wring.online/?token=error');
console.log("Token Error ", tokenError);
})
}).catch((permissionError)=>{
//window.location.assign('https://www.wring.online/?permission=error');
console.log("permission Error ", permissionError);
})
}).catch((registrationError)=>{
//window.location.assign('https://www.wring.online/?swregistration=error');
console.log("registration Error ", registrationError);
})
}
else{ // browser does not support service workers
window.location.assign('https://www.wring.online/?sw=notsupported');
}
}
})
// handle incoming messages - may not require a notification alert if page already open
messaging.onMessage((payload)=>{console.log("On Message - payload received ", payload)});
</script>
Customised service worker
Almost all firebase documentation will mention the requirement of a service worker named “firebase-messaging-sw.js” to be created and stored in the root directory
Wix doesn’t allow this, so the workaround is to use Wix’s http-functions.js to create our own service worker
Here is a sample:
import { ok, notFound, created, serverError } from 'wix-http-functions';
let firebase_messaging_sw_js = `
importScripts('https://www.gstatic.com/firebasejs/8.3.2/firebase-app.js')
importScripts('https://www.gstatic.com/firebasejs/8.3.2/firebase-messaging.js')
firebase.initializeApp({
apiKey: "==========================",
authDomain: "xxxxxx.firebaseapp.com",
projectId: "xxxxxxxx",
storageBucket: "xxxxxxxxxx.appspot.com",
messagingSenderId: "xxxxxxxxxxxxxxxxxx",
appId: "xxxxxxxxxxxxxxxxxxxxxx",
measurementId: "#############"
})
const messaging = firebase.messaging();
messaging.onBackgroundMessage((payload) => {
console.log('[firebase-messaging-sw.js] Received background message ', payload);
// Customize notification here
const notificationTitle = payload.notification.title;
const notificationOptions = {
body: payload.notification.body
};
self.registration.showNotification(notificationTitle,
notificationOptions);
});`
export function get_firebase_messaging_sw_js(request) { console.log("get firebase messaging sw js with request ", request); let options = { "headers": { "Content-Type": "application/javascript" }, "body": firebase_messaging_sw_js }; return ok(options); }
Server side:
Install firebase-admin npm module
(Only required if sending notifications programatically from the server)
related links:
Add the Firebase Admin SDK to your server
https://www.tuberelevant.com/post/https-push-notifications-in-wix
https://www.wix.com/velo/forum/coding-with-velo/adding-ads-txt-file
Thanks for sharing! I'm moving this to our Tips, Tutorials, Examples category.