溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

怎么推送Web瀏覽器的通知

發(fā)布時(shí)間:2021-11-04 16:36:51 來源:億速云 閱讀:145 作者:柒染 欄目:建站服務(wù)器

這篇文章給大家介紹怎么推送Web瀏覽器的通知,內(nèi)容非常詳細(xì),感興趣的小伙伴們可以參考借鑒,希望對(duì)大家能有所幫助。

你如何增加網(wǎng)站的流量?電子商務(wù)企業(yè)的主要目標(biāo)是繼續(xù)吸引現(xiàn)有用戶并吸引新訪客。通過發(fā)送電子郵件通知,短信提醒,社交媒體和網(wǎng)絡(luò)推送通知,有很多方法可以增加網(wǎng)站流量和客戶互動(dòng)度。今天,我們將看到推送通知如何適用于Web瀏覽器。這些是通過桌面和移動(dòng)瀏覽器發(fā)送給用戶的通知。這些通知在用戶的桌面或移動(dòng)瀏覽器上提供 - 無(wú)論用戶是否在網(wǎng)站上。這些通知允許用戶從他們喜歡的網(wǎng)站獲得及時(shí)更新,并允許開發(fā)人員有效地重新使用相關(guān)內(nèi)容以增加網(wǎng)站的流量。

怎么推送Web瀏覽器的通知


此項(xiàng)目需要以下項(xiàng)目

Website
前端網(wǎng)站,您必須在index.html中包含jav.json文件

manifest.json
有關(guān)您的網(wǎng)站擴(kuò)展的基本元數(shù)據(jù)信息,這將幫助您與瀏覽器操作進(jìn)行通信。

service-worker.js
這是一個(gè)腳本文件,您的瀏覽器在后臺(tái)運(yùn)行并執(zhí)行同步操作。

notification.js
允許瀏覽器通知的JavaScript文件。這包含將用戶注冊(cè)令牌信息發(fā)送到后端服務(wù)器的所有操作。

RESTful或ServerSide URL 

Subscribe
創(chuàng)建一個(gè)簡(jiǎn)單的服務(wù)端插入操作來存儲(chǔ)用戶注冊(cè)令牌。

Unsubscribe
以同樣的方式創(chuàng)建刪除操作以從數(shù)據(jù)庫(kù)中刪除用戶注冊(cè)令牌。

Get Notification
此URL應(yīng)以JSON數(shù)據(jù)格式返回通知數(shù)據(jù)。

CURL推送通知應(yīng)用程序
服務(wù)器端CURL項(xiàng)目,用于向訂閱用戶列表發(fā)送通知。

數(shù)據(jù)庫(kù)
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)
}


Firebase入門

第1步為Google Cloud Messing
創(chuàng)建Firebase項(xiàng)目。

怎么推送Web瀏覽器的通知


步驟2
登錄Google Developer Console并轉(zhuǎn)到您的信息中心

怎么推送Web瀏覽器的通知


步驟3
同意firebase條款。

怎么推送Web瀏覽器的通知


步驟3
選擇您的API項(xiàng)目。

怎么推送Web瀏覽器的通知


步驟4
單擊“選擇”并選擇現(xiàn)有的Firebase項(xiàng)目。怎么推送Web瀏覽器的通知

步驟5
選擇現(xiàn)有項(xiàng)目

怎么推送Web瀏覽器的通知


步驟6
復(fù)制項(xiàng)目身份驗(yàn)證密鑰以發(fā)送Google Cloud Messaing 怎么推送Web瀏覽器的通知

步驟7
您的項(xiàng)目客戶端ID。

怎么推送Web瀏覽器的通知



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.

<!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

</button>

</div>

<script src="notification.js"></script>

</body>

</html>


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 <span class='high'>Allow</span> 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.

<?php

function sendGCM($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 title, message, logo and url inputs. Make sure give 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 form data and sending the push notications to registred 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 insert notification information and getting all the registration ids. 

<?php

class gcmClass

{

   public function getIDs()

  {

   try{

     $db = getDB();

     $stmt = $db->prepare("SELECT rid FROM GMC");

     $stmt->execute();

     $data=$stmt->fetchALL(PDO::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();

   return true;

  }

  catch(PDOException $e) {

   echo '{"error":{"text":'. $e->getMessage() .'}}';

   }

 }

}

?>


config.php
Database configuration file. You have to modify 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');

function getDB()

{

    $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();

?>

關(guān)于怎么推送Web瀏覽器的通知就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

web
AI