Push notifications for Web browsers


March 21, 2018

How do you increase site traffic? The main objective of e-commerce companies is to continue to involve existing subscribers and get new visitors. There are many ways to increase site traffic and customer engagement by sending e-mail notifications, SMS alerts, social media and web push notifications. Today we will see how push notifications for web browsers work. These are the notifications that are sent to users via desktop and mobile browsers. These notifications are provided on the user’s desktop or mobile browser, regardless of whether or not the user is on the Web site. These notifications allow users to get timely updates from the sites they love and allow developers to engage again with relevant content to increase site traffic. Let’s start how it works.

Push Notifications for Web Browsers

This project is required by following the articles

Website
On the Frontend Web site, you must include the manifest.json file in the index.html

manifest.json
Basic metadata information about the extension of your website, this will help you communicate with browser actions.

Service-worker.js
This is a script file that the browser runs in the background and performs synchronization operations.

notification.js
A JavaScript file to allow browser notification. This has all actions to send user registration token information to the back-end server.

RESTful URL or ServerSide

subscribe
Create a simple service-side operation to store the user registration token.

Unsubscribe
Likewise, it creates a delete operation to delete the user registration token from the database.

Get notification
This URL should return a notification data in the JSON data format.

CURL push notification application
A server-side CURL project to send notifications to the list of registered users.

database
You must create a database to store user registration IDs / tokens.
CREATE TABLE GMC {
gid INT PRIMARY KEY AUTO_INCREMENT,
free the TEXT
}

This will contain a push notification data.
CREATE TABLE notifications {
nid INT PRIMARY KEY AUTO_INCREMENT,
title VARCHAR (200),
msg VARCHAR (200),
logo VARCHAR (300),
name VARCHAR (100),
url VARCHAR (300)
}

Start with Firebase

Step 1
Create a Firebase project for Google Cloud Messing.

Firebase application for GCM FCM ID
Firebase application for the FCM GCM ID

Step 2
Log in to the Google Developer Console and go to your Dashboard

Firebase application for GCM FCM ID
Firebase application for the FCM GCM ID

Step 3
Accept the terms of Firebase.

Firebase application for GCM FCM ID
Firebase application for the FCM GCM ID

Step 3
Select your API project.

Firebase application for GCM FCM ID
Firebase application for the FCM GCM ID

Step 4
Click select and choose the existing Firebase project. Firebase application for the FCM GCM ID

Firebase application for GCM FCM ID

Step 5
Choose the existing project

Firebase application for GCM FCM ID
Firebase application for the FCM GCM ID

Step 6
Copy the project authentication key to send the Google Cloud MessaingFirebase application for the FCM GCM ID

Firebase application for GCM FCM ID

Step 7
Your project client id.

FiID
FiID

manifest.json
Metadata information file to communicate with browsers. Here you include your project client id, check the image of step 7.
{
“name”: “Web Push Demo”,
“short_name”: “push_demo”,
“version”: “1.0.0”,
“description”: “A simple website with push notification”,
“author”: {
“name”: “Srinivas Tamada”
},
“gcm_sender_id”: “Your_Client_ID”,
“gcm_user_visible_only”: true
}

Service-worker.js
JavaScript file that the browser runs in the background and performs synchronization operations. This will always communicate with the project API to get the latest notification information. Upload this file to the location of the project index.
var auto = this;
var urlMain;
self.addEventListener (“push”, function (event) {
event.waitUntil (
fetch (“https://yourwebiste.com/api/getNotification”, {
method: “get”
})
.then (function (response) {
return response.json ();
})
.then (function (result) {

urlMain = result.data.url;
const options = {
body: result.data.msg,
icon: result.data.logo,
image: result.data.name,
action: result.data.url
};
self.registration.showNotification (result.data.title, options);
})
);
});

self.addEventListener (“notificationclick”, function (event) {
event.notification.close ();
const promiseChain = clients.openWindow (urlMain);
event.waitUntil (promiseChain);
});

index.html
Include the manifest.json and notification.js file. Qui notification.js is a controller and works with service-worker.js.
<! DOCTYPE html>
<Html>
<Head>
<title> Push Demo </ title>
<link rel = “manifest” href = “manifest.json”>
</ Head>
<Body>
<div id = “container”>
<div class = “desc”> </ div>
<button class = “pushButton” disabled>
subscribe
<Key />
</ Div>
<script src = “notification.js”> </ script>
</ Body>
</ Html>

notification.js
JavaScript files to check all subscriber information. Large file bits divided into different parts.

DocumentContent Loader starts the service worker and this will verify the user’s subscription. This code will start the Allow and Block popup.
var isPushEnabled = false;
var pushButton = document.querySelector (“. pushButton”);
var desc = document.querySelector (“. desc”);
var disableText = “Unsubscribe”;
var enableText = “Subscribe”;
var disableDesc = “Thank you message”;
var enableDesc = “Click <span class = ‘high’> Allow </ span> button at the top left.”;

document.addEventListener (“DOMContentLoaded”, function () {
if (isPushEnabled) {
Unsubscribe ();
} other {
subscribe ();
}
serviceWorkerCall ();
});

The serviceWorkerCall function will register the server-worker.js with the initilise function for future actions.
function serviceWorkerCall () {
if (“serviceWorker” in the browser) {
navigator.serviceWorker.register (“/ service-worker.js”)
.then (initialiseState);
} other {
console.warn (“Service workers are not supported in this browser.”);
}
}

function initialiseState () {
if (! (“showNotification” in ServiceWorkerRegistration.prototype)) {
console.log (“Notifications not supported.”);
return;
}

if (Notification.permission === “denied”) {
console.log (“User has blocked notifications.”);
return;
}

if (! (“PushManager” in the window)) {
console.log (“Push messaging is not supported.”);
return;
}

navigator.serviceWorker.ready.then (function (serviceWorkerRegistration) {
serviceWorkerRegistration.pushManager
.getSubscription ()
.then (function (subscription) {
pushButton.disabled = false;
if (! subscription) {
return;
}
if (subscription) {
sendSubscriptionToServer (subscription);
}

pushButton.textContent = disableText;
desc.textContent = disableDesc;
isPushEnabled = true;
})
.catch (function (e) {
console.log (“Error during getSubscription ()”, e);
});
});
}

subscribe and unsubscribe the function to change the message and the status of the button.
function subscribe () {
pushButton.disabled = true;
navigator.serviceWorker.ready.then (function (serviceWorkerRegistration) {
serviceWorkerRegistration.pushManager
.subscribe ({userVisibleOnly: true})
.then (function (subscription) {
isPushEnabled = true;
pushButton.textContent = disableText;
desc.textContent = disableDesc;
pushButton.disabled = false;
if (subscription) {
sendSubscriptionToServer (subscription);
}
})
.catch (function (e) {
if (Notification.permission === “denied”) {
console.warn (“Permission for notification denied”);
pushButton.disabled = true;
} other {
console.error (“Unable to subscribe to push”, e);
pushButton.disabled = true;
pushButton.textContent = “Enable push messages”;
}
});
});
}

function unsubscribe () {
pushButton.disabled = true;
navigator.serviceWorker.ready.then (function (serviceWorkerRegistration) {
serviceWorkerRegistration.pushManager
.getSubscription ()
.then (function (pushSubscription) {
if (! pushSubscription) {
isPushEnabled = false;
pushButton.disabled = false;
pushButton.textContent = enableText;
desc.textContent = enableDesc;
return;
}

var temp = pushSubscription.endpoint.split (“/”);
var registration_id = temp [temp.length – 1];
deleteSubscriptionToServer (registration_id);

pushSubscription.unsubscribe (). then (function (successful) {
pushButton.disabled = false;
pushButton.textContent = enableText;
desc.textContent = enableDesc;
isPushEnabled = false;
})
.catch (function (e) {
console.error (“Error generated during unsubscription from push messages.”);
});
});
});
}

Information about functions call these following functions. Ajax calls to store and delete user registration IDs.
// send the subscription ID to the server
function sendSubscriptionToServer (subscription) {
var temp = subscription.endpoint.split (“/”);
var registration_id = temp [temp.length – 1];
fetch (
“http://yourwebsite.com/api/insertGCM/” + registration_id,
{
method: “get”
}
) .then (function (response) {
return response.json ();
});
}

function deleteSubscriptionToServer (rid) {
recovers (“https://yourwebsite.com/api/deleteGCM/” + reduce, {
method: “get”
}). then (function (response) {
return response.json ();
});
}

InsertGCM
PHP code to enter the registration ID in the GCM table. Alwasy checks HTTP_ORIGIN to avoid incorrect input.
function insertGCM ($ rid) {
$ check = false;
if ($ _ SERVER [‘HTTP_ORIGIN’] && $ _SERVER [‘HTTP_ORIGIN’] == “http://yourwesbite.com”) {
$ check = true;
}

if ($ check) {
$ db = getDB ();
$ sql1 = “SELECT * FROM GMC WHERE rid =: rid”;
$ stmt1 = $ db-> prepare ($ sql1);
$ stmt1-> bindParam (“rid”, $ rid, PDO :: PARAM_STR);
$ Stmt1-> execute ();
$ MainCount = $ stmt1-> rowCount ();
if ($ mainCount <1) {
$ sql = “INSERT THE GMC VALUES (reduce) (: laugh)”;
$ stmt = $ db-> prepare ($ sql);
$ stmt-> bindParam (“rid”, $ rid, PDO :: PARAM_STR);
$ Stmt-> execute ();
echo ‘{“success”: {“text”: “done”}}’;
}
other{
echo ‘{“success”: {“text”: “already users”}}’;
}
}
other{
echo ‘{“error”: {“text”: “No login”}}’;
}
}

Delete
Deletes the GCM table data based on the registration ID.
function deleteGCM ($ rid) {
$ check = false;
if ($ _ SERVER [‘HTTP_ORIGIN’] && $ _SERVER [‘HTTP_ORIGIN’] == “https://push.9lessons.info”) {
$ check = true;
}

if ($ check) {
$ db = getDB ();
$ sql = “DELETE FROM GMC WHERE rid =: ridi”;
$ stmt = $ db-> prepare ($ sql);
$ stmt-> bindParam (“rid”, $ rid, PDO :: PARAM_STR);
$ Stmt-> execute ();
echo ‘{“success”: {“text”: “done”}}’;
}
other{
echo ‘{“error”: {“text”: “No login”}}’;
}
}

Get notification
Get the latest notification for service-worker.js
function getNotification () {
$ db = getDB ();
$ sql1 = “SELECT title, msg, logo, url, name from notifications FROM ORDER BY nid DESC LIMIT 1”;
$ stmt1 = $ db-> prepare ($ sql1);
$ Stmt1-> execute ();
$ notification = $ stmt1-> fetch (PDO :: FETCH_OBJ);
$ notification-> action = $ notification-> url;
$ notification-> click_action = $ notification-> url;
if ($ notification) {
$ notification = json_encode ($ notification);
echo ‘{“data”:’. $ notification. ‘}’;
}
}

Administrator for sending push notifications

SendGCM.php
PHP Curl to communicate with Google Firebase APIs. Edit Your_Authorization_API and check step 6.
<? Php
sendGCM function ($ fields) {
$ url = ‘https://fcm.googleapis.com/fcm/send’;
$ fields = json_encode ($ fields);
$ headers = array (
‘Authorization: key =’. “Your_Authorization_Key”
‘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_IPRESOLVE, CURL_IPRESOLVE_V4);
curl_setopt ($ ch, CURLOPT_POSTFIELDS, $ fields);
$ result = curl_exec ($ ch);
echo $ result;
curl_close ($ ch);
}
?>

Push notification form
Simple HTML form with input title, message, logo and url. Be sure to provide some authentication / login to protect this page.
<form autocomplete = “off” method = “post” action = “”>
<Div>
<Label> Title </ label>
<input type = “text” placeholder = “Title” name = “title”>
</ Div>
<Div>
<Label> Message </ label>
<input type = “text” placeholder = “Message” name = “msg”>
</ Div>
<Div>
<Label> Logo </ label>
<input type = “text” placeholder = “Logo” name = “logo” value = “”>
</ Div>
<Div>
<Label> Name </ label>
<input type = “text” placeholder = “Name” name = “name”>
</ Div>
<Div>
<Label> URL </ label>
<input type = “text” placeholder = “URL” name = “url”>
</ Div>
<Div>
<input type = “submit” value = “Push Notification” name = “notificationSubmit” />
</ Div>
</ Form>

home.php
This will insert the form data and send push notifications to registered users by calling $ gcm-> getIDs ()
<? Php
include (‘config.php’);
include (‘sendGMC.php’);
if (! empty ($ _ POST [‘notificationSubmit’])) {
$ Title = $ _ POST [‘title’];
$ Msg = $ _ POST [‘msg’];
$ Logo = $ _ POST [‘logo’];
$ Name = $ _ POST [‘name’];
$ Url = $ _ POST [‘url’];
if (strlen (trim ($ title))> 1 && strlen (trim ($ msg))> 1 && strlen (trim ($ logo))> 1 && strlen (trim ($ name))> 1 && strlen (trim ( $ url))> 1)
{
if ($ gcmClass-> insertNotification ($ title, $ msg, $ logo, $ name, $ url)) {
$ registrationId = $ gcmClass-> getIDs ();
$ Total_rids = [];
foreach ($ registrationId as $ r) {
array_push ($ total_rids, $ r-> rid);
}
$ fields = array (‘registration_ids’ => $ total_rids);
sendGCM (fields $);
echo “Done”;
}
}
}
include (‘header.php’);
?>

gcmClass.php
PHP class for information on insert notification and get all registration IDs.
<? Php
gcmClass class
{
getIDs public function ()
{
try{
$ db = getDB ();
$ stmt = $ db-> prepare (“SELECT REDUCTION FROM GMC”);
$ Stmt-> execute ();
$ data = $ stmt-> fetchAll (DOP :: FETCH_OBJ);
return $ data;
}
catch (PDOException $ e) {
echo ‘{“error”: {“text”:’. $ e-> getMessage (). ‘}}’;
}
}

public function insertNotification ($ a, $ b, $ c, $ d, $ e)
{
try{
$ db = getDB ();
$ stmt = $ db-> prepare (“INSERT INTO notifications (title, msg, logo, name, url) VALUES (: title,: msg ,: logo,: name,: url)”);
$ stmt-> bindParam (“title”, $ a, PDO :: PARAM_STR);
$ stmt-> bindParam (“msg”, $ b, PDO :: PARAM_STR);
$ stmt-> bindParam (“logo”, $ c, PDO :: PARAM_STR);
$ stmt-> bindParam (“name”, $ d, PDO :: PARAM_STR);
$ stmt-> bindParam (“url”, $ e, PDO :: PARAM_STR);
$ Stmt-> execute ();
come back true;
}
catch (PDOException $ e) {
echo ‘{“error”: {“text”:’. $ e-> getMessage (). ‘}}’;
}
}
}
?>

config.php
Database configuration file. You must change the database username and password.
<? Php
/ * DATABASE CONFIGURATION * /
define (‘DB_SERVER’, ‘localhost’);
define (‘DB_USERNAME’, ‘username’);
define (‘DB_PASSWORD’, ‘password’);
define (‘DB_DATABASE’, ‘database’);
define (“BASE_URL”, “https://www.yourwebsite.com/”);
define (“SITE_KEY”, “yourSecretKeyyx”);

getDB () function
{
$ Dbhost = DB_SERVER;
$ Dbuser = DB_USERNAME;
$ Dbpass = DB_PASSWORD;
$ Dbname = DB_DATABASE;
$ dbConnection = new PDO (“mysql: host = $ dbhost; dbname = $ dbname”, $ dbuser, $ dbpass);
$ dbConnection-> exec (“set names utf8”);
$ dbConnection-> setAttribute (PDO :: ATTR_ERRMODE, PDO :: ERRMODE_EXCEPTION);
return $ dbConnection;
}
include (‘class / gcmClass.php’);
$ gcmClass = new gcmClass ();
?>

Leave a Reply

Your email address will not be published.