In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >
Share
Shulou(Shulou.com)06/01 Report--
This article introduces you how to push Web browser notice, the content is very detailed, interested friends can refer to, hope to be helpful to you.
How do you increase the traffic to your website? The main goal of e-commerce enterprises is to continue to attract existing users and new visitors. There are many ways to increase website traffic and customer interaction by sending email notifications, SMS alerts, social media and online push notifications. Today, we will see how push notifications apply to Web browsers. These are notifications sent to users through desktops and mobile browsers. These notifications are provided on the user's desktop or mobile browser-whether the user is on the site or not. These notifications allow users to get timely updates from their favorite sites and allow developers to effectively reuse relevant content to increase traffic to the site.
This project requires the following items
Website
Front-end website, you must include the jav.json file in the index.html
Manifest.json
Basic metadata information about your site extensions, which will help you communicate with browser operations.
Service-worker.js
This is a script file that your browser runs in the background and performs synchronization operations.
Notification.js
JavaScript files that allow browsers to notify. This includes all operations to send user registration token information to the back-end server.
RESTful or ServerSide URL
Subscribe
Create a simple server-side insert operation to store the user registration token.
Unsubscribe
Create a delete operation in the same way to delete a user registration token from the database.
Get Notification
This URL should return notification data in JSON data format.
CURL push Notification Application
A server-side CURL project that sends notifications to the list of subscribers.
Database
You have to create a database for storing user registration ids/tokens.
CREATE TABLE GMC {
Gid INT PRIMARY KEY AUTO_INCREMENT
Rid 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)
}
Getting started with Firebase
The first step is Google Cloud Messing
Create a Firebase project.
Step 2
Log in to Google Developer Console and go to your information center
Step 3
Agree to the terms of firebase.
Step 3
Select your API project.
Step 4
Click Select and select an existing Firebase project.
Step 5
Select an existing project
Step 6
Copy the project authentication key to send Google Cloud Messaing
Step 7
Your project client ID.
Manifest.json
Meta data information file to communicate with browsers. Here include your project client id, check Step 7 screenshot.
{
"name": "Web Push Demo"
"short_name": "push_demo"
"version": "1.0.0"
"description": "A simple site with push notification"
"author": {
"name": "Srinivas Tamada"
}
"gcm_sender_id": "Your_Client_ID"
"gcm_user_visible_only": true
}
Service-worker.js
JavaScript file that your browser runs at the background and perform sync operations. This will always communicate with your project api to get latest notification information. Upload this file in your project index location.
Var self = 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 manifest.json and notification.js file. Here notification.js is a controller and this works with service-worker.js.
Push Demo
Subscribe
Notification.js
JavaScript file to control all the subscribers' information. Bit large file split into different parts.
DocumentContent Loader initilise the service worker and this will verify the user subscription. This Code will launch 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 Allow button top left."
Document.addEventListener ("DOMContentLoaded", function () {
If (isPushEnabled) {
Unsubscribe ()
} else {
Subscribe ()
}
ServiceWorkerCall ()
});
ServiceWorkerCall function will register the server-worker.js with initilise function for future actions.
Function serviceWorkerCall () {
If ("serviceWorker" in navigator) {
Navigator.serviceWorker.register ("/ service-worker.js")
.then (initialiseState)
} else {
Console.warn ("Service workers aren't supported in this browser.")
}
}
Function initialiseState () {
If (! ("showNotification" in ServiceWorkerRegistration.prototype)) {
Console.log ("Notifications aren't supported.")
Return
}
If (Notification.permission = = "denied") {
Console.log ("The user has blocked notifications.")
Return
}
If (! ("PushManager" in window)) {
Console.log ("Push messaging isn't 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 function to change the message and button status.
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 is denied")
PushButton.disabled = true
} else {
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 thrown while unsbscribing from push messaging.")
});
});
});
}
About functions are calling these following functions. Ajax calls to store and delete the user's registation ids.
/ / send subscription id to 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) {
Fetch ("https://yourwebsite.com/api/deleteGCM/" + rid, {
Method: "get"
}) .then (function (response) {
Return response.json ()
});
}
InsertGCM
PHP code to insert registartion id in GCM table. Alwasy check HTTP_ORIGIN to avoid wrong inputs.
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 INTO GMC(rid) VALUES (:rid)"; $stmt = $db->Prepare ($sql)
$stmt- > bindParam ("rid", $rid,PDO::PARAM_STR)
$stmt- > execute ()
Echo'{"success": {"text": "done"}'
}
Else {
Echo'{"success": {"text": "already users"}'
}
}
Else {
Echo'{"error": {"text": "No access"}'
}
}
Delete
Delete 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=:rid"
$stmt = $db- > prepare ($sql)
$stmt- > bindParam ("rid", $rid,PDO::PARAM_STR)
$stmt- > execute ()
Echo'{"success": {"text": "done"}'
}
Else {
Echo'{"error": {"text": "No access"}'
}
}
GetNotification
Get latest notifiaction for service-worker.js
Function getNotification () {
$db = getDB ()
$sql1 = "SELECT title, msg, logo, url, name FROM notifications ORDER BYnid 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 NotificationsSendGCM.php
PHP Curl to communcate with Google Firebase APIs. Modify Your_Authorization_API and check Step 6.
Push Notification Form
Simple HTML form with title, message, logo and url inputs. Make sure give some authentication/login to protect this page.
Title
Message
Logo
Name
URL
Home.php
This will insert form data and sending the push notications to registred users by calling $gcm- > getIDs ()
GcmClass.php
PHP class for insert notification information and getting all the registration ids.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.