How to send push notification to web browser by using Firebase?

Step 1: Go to https://firebase.google.com/

Step 2: Click on Get Started

Step 3: Click on Add project

Step 4: Create project name like Web push notification and click on Continue

Once your project create then your dashboard look like this.

Step 5: Click on Web code button

Step 6: Add your app name and click on Register app

Copy above code into some text file so that will be use in further part.

Note*: You must have https domain then and then you can create your web push notification for your website

Step 7: Now we are creating one folder notification inside www folder

Step 8: After that you need to create one file like my_application.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Shinerweb.come web push notification</title>
</head>
<body>
<h2>Firebase Web Push Notification by <a href="https://shinerweb.com/">shinerweb.com</a></h2>

<p id="token"></p>
<script src="https://www.gstatic.com/firebasejs/7.14.6/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.14.6/firebase-messaging.js"></script>
<script>
    var firebaseConfig = {
         apiKey: "AIzaSyB1URa71TLghCtX-8syKfEIXGMpFd0gnSc",
		  authDomain: "web-push-notification-d46c2.firebaseapp.com",
		  projectId: "web-push-notification-d46c2",
		  storageBucket: "web-push-notification-d46c2.appspot.com",
		  messagingSenderId: "533936087912",
		  appId: "1:533936087912:web:08911f9331e34e8905ecdd",
		  measurementId: "G-NM0JB5R7K9"
    };
    firebase.initializeApp(firebaseConfig);
    const messaging=firebase.messaging();

    function IntitalizeFireBaseMessaging() {
        messaging
            .requestPermission()
            .then(function () {
                console.log("Notification Permission");
                return messaging.getToken();
            })
            .then(function (token) {
                console.log("Token : "+token);
                document.getElementById("token").innerHTML=token;
            })
            .catch(function (reason) {
                console.log(reason);
            });
    }

    messaging.onMessage(function (payload) {
        console.log(payload);
        const notificationOption={
            body:payload.notification.body,
            icon:payload.notification.icon
        };

        if(Notification.permission==="granted"){
            var notification=new Notification(payload.notification.title,notificationOption);

            notification.onclick=function (ev) {
                ev.preventDefault();
                window.open(payload.notification.click_action,'_blank');
                notification.close();
            }
        }

    });
    messaging.onTokenRefresh(function () {
        messaging.getToken()
            .then(function (newtoken) {
                console.log("New Token : "+ newtoken);
            })
            .catch(function (reason) {
                console.log(reason);
				//alert(reason);
            })
    })
    IntitalizeFireBaseMessaging();
</script>
</body>
</html>

In above code you can change your firebaseConfig details

Step 9: One more file you need to create like send_notification.php

<form method="post" action="send_notification.php">
Title<input type="text" name="title">
Message<input type="text" name="message">
<!--Icon path<input type="text" name="icon">-->
Token<input type="text" name="token">
<input type="submit" value="Send notification">
</form>

<?php
function sendNotification(){
    $url ="https://fcm.googleapis.com/fcm/send";

    $fields=array(
        "to"=>$_REQUEST['token'],
        "notification"=>array(
            "body"=>$_REQUEST['message'],
            "title"=>$_REQUEST['title'],
            "icon"=>$_REQUEST['icon'],
            "click_action"=>"https://shinerweb.com"
        )
    );

    $headers=array(
        'Authorization: key=AAAAfFESI2g:APA91bGgY1EqDggzH-AJGEoOSjtGPjS-X6Hmvs1A9iX-RmlhDzuwh4GqlM2t0lDkjaCYs7vZgyXKiK_niP-5QuTjSaqYjy0uqLXpnItu0CSoDylnNk0_-mHBp25aGzD_ugh8Xzfodgcm',
        'Content-Type:application/json'
    );

    $ch=curl_init();
    curl_setopt($ch,CURLOPT_URL,$url);
    curl_setopt($ch,CURLOPT_POST,true);
    curl_setopt($ch,CURLOPT_HTTPHEADER,$headers);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
    curl_setopt($ch,CURLOPT_POSTFIELDS,json_encode($fields));
    $result=curl_exec($ch);
    print_r($result);
    curl_close($ch);
}
sendNotification();

Here you need to add your server key in above code ‘Authorization: key=YOUR_SERVER_KEY’

Step 10: After creating above two files you must have to create one file firebase-messaging-sw.js at root level

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

var firebaseConfig = {
	apiKey: "AIzaSyB1URa71TLghCtX-8syKfEIXGMpFd0gnSc",
	  authDomain: "web-push-notification-d46c2.firebaseapp.com",
	  projectId: "web-push-notification-d46c2",
	  storageBucket: "web-push-notification-d46c2.appspot.com",
	  messagingSenderId: "533936087912",
	  appId: "1:533936087912:web:08911f9331e34e8905ecdd",
	  measurementId: "G-NM0JB5R7K9"
};

firebase.initializeApp(firebaseConfig);
const messaging=firebase.messaging();

messaging.setBackgroundMessageHandler(function (payload) {
    console.log(payload);
    const notification=JSON.parse(payload);
    const notificationOption={
        body:notification.body,
        icon:notification.icon
    };
    return self.registration.showNotification(payload.notification.title,notificationOption);
});

Note*: There is also change your firebaseConfig data

Step 11: Now finally we need to test our notification so we follow below link with open my_application.html file

https://shinerweb.com/notification/my_application.html

When you hit above link then can able display one popup for show notification so you just click on Allow button

Once you allow the wait for few minutes then you can see one token number as below

Step 12: Now send notification from send_notification.php file

https://shinerweb.com/notification/send_notification.php

Note* : Copy past token which you generated from my_application.html file

Everything is working fine and you will get any problem then please comment and I will try to resolve your problem.

Related Posts

Divyesh Patel

I'm Divyesh Patel, Web & App developer. I want to make things that make a difference. With every line of code, i strive to make the web a beautiful place.

This Post Has 3 Comments

  1. Hi Divyesh,

    Have tried implementing your code and not getting issues. Sending a notification however is not working.
    HTTPS: yes
    Allow notifications action: worked
    Cookie: yes
    Send notification: filled in the fields and pressed button. No issues nor a notification.

    Do not know what to look for.

    Regards,
    Jasper

Leave a Reply