HTML 5 TutorialsHow to send web notifications in HTML5

How to send web notifications in HTML5

In our blog today we will write a simple program to send web notifications from a server to a web page. We can use SSE in HTML5,SSE stands for Server Sent Events. It means whenever a new update is available on the server it sends notification to the user and show the current notification. We will write a simple PHP and HTML page which we will put in a local server or you can put it in a web server if you have access to one.

Our PHP page will take the server time and will send it to the html page as web notification. Lets get started

<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<body>
<h1>UPDATED TIME</h1>
<div id="output"></div>

In the above code we define to generate an id named as output,which we can use in script and will help us in finding the element.

<script>
if(typeof(EventSource)!=="undefined")
  {
  var source=new EventSource("server.php");
  source.onmessage=function(event)
    {
    document.getElementById("output").innerHTML+=event.data + "<br>";
    };
  }

We create a new event source here and in the braces we pass the value or URL whose update is to be found or sent to the user. When the update is found it fires the function and send the update to the user. Next we get the element by id from the document and sets its inner HTML property to new data means event data and a line break. Line break simply means a new data.

else
  {
  document.getElementById("result").innerHTML="Sorry, your browser does not support this feature :( ";
  }
</script>

</body>
</html>

If your browser does not support the feature then this error message is shown on the screen.

Let us now create the PHP page.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Server</title>
</head>

<body>
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');

$time = date('r');
echo "data: The updated time is: {$time}nn";
flush();
?>
</body>
</html>

The PHP page just checks the time and notify the web page.

Execution

Copy both the HTML file and the PHP file in the Htdoc folder of your webserver. I am doing it locally. Visit the page
http://localhost/web_not.html I named the html page web_not.html You can name it whatever you want.
The output is

output_web_noti

Exclusive content

- Advertisement -

Latest article

21,501FansLike
4,106FollowersFollow
106,000SubscribersSubscribe

More article

- Advertisement -