How to send the push notification to browser using html5 and javascript ?


How to send the push notification to the browser using html5 and javascript?


Asked by:- RameshwarLate
1
: 619 At:- 12/25/2017 11:17:31 AM
Html javascript






1 Answers
profileImage Answered by:- Sam

firefox and chrome, both have notification api for this, which you can access using javascript and send html5 push notifications (as chrome doesn't allow us to call notification API from iframe so would not be able to provide fiddle for chrome, but this https://jsfiddle.net/robnyman/TuJHx/ works in firefox)

Here is the complete JS code, which you should test by creating a separate .html file

<script type="text/javascript">
        // Determine the correct object to use
        var notification = window.Notification || window.mozNotification || window.webkitNotification;

        // The user needs to allow this
        if ('undefined' === typeof notification)
            alert('Web notification not supported');
        else
            notification.requestPermission(function (permission) { });

        // A function handler
        function Notify(titleText, bodyText) {
            if ('undefined' === typeof notification)
                return false;       //Not supported....
            var noty = new notification(
                titleText, {
                    body: bodyText,
                    dir: 'auto', // or ltr, rtl
                    lang: 'EN', //lang used within the notification.
                    tag: 'notificationPopup', //An element ID to get/set the content
                    icon: '' //The URL of an image to be used as an icon
                }
            );
            noty.onclick = function () {
                console.log('notification.Click');
            };
            noty.onerror = function () {
                console.log('notification.Error');
            };
            noty.onshow = function () {
                console.log('notification.Show');
            };
            noty.onclose = function () {
                console.log('notification.Close');
            };
            return true;
        }

        document.addEventListener('visibilitychange', visibleChangeHandler, false);
        var notification = window.Notification || window.mozNotification || window.webkitNotification;
        notification.requestPermission(function (permission) { });

        //Poll our backend for notifications, set some reasonable timeout for your application
        window.setInterval(function () {
            console.log('poll...');
              // call ajax etc here
            notificationPoster("Testing", "1");
        }, 5000);    //poll every 5 secs.

        var originalTitle = '', messageCount = 0;
        function notificationPoster(data, status) {
            if (document['hidden']) {
                console.log('page not visible, use notification and vibrate');
                //Vibrate and try to send notification
                window.navigator.vibrate(500);
                if (false == Notify(data.title, data.body)) {
                    //Fallback signaling which updates the tab title
                    if ('' == originalTitle)
                        originalTitle = document.title;
                    messageCount++;
                    document.title = '(' + messageCount + ' messages!) ' + originalTitle;
                } else {
                    //Notification was shown
                }
            }
            else {
                console.log('page visible, push to normal notification queue');
                doYourOwnSignaling(data);

                //Reset fallback handling
                messageCount = 0;
                if ('' != originalTitle)
                    document.title = originalTitle;
                originalTitle = '';
            }
        }
	</script>

Output:

output-html5-push-notification-using-javascript-min.png

Another solution to try, create a new html file and copy paste below code

<!DOCTYPE html>
<html lang="en" dir="ltr" xmlns:fb="http://ogp.me/ns/fb#">
<head>
    
</head>
<body>




<div class="demo-wrapper">

<h1>Demo:  Web Notifications API</h1>

<div class="demo-conversion">Read <a href="https://davidwalsh.name/notifications-api" target="_top">Web Notifications API</a></div>

<div id="promoNode"></div>
	
	<p>Click the button below to show a notification.  They appear different in different browsers.</p>

	<p><button onclick="showNotification()">Show a Notification</button></p>
	
	<script type="text/javascript">
		function showNotification() {
			if(window.Notification) {
				Notification.requestPermission(function(status) { 
					console.log('Status: ', status); 
					var n = new Notification('Title', { body: 'I am the body text!' }); 
				});
			}
			else {
				alert('Your browser doesn\'t support notifications.');
			}
		}
	</script>	
	
</div>




</body>
</html>

the above code will work to send push notificaitons in Chrome & firefox, either you can use fiddle code, or the above one, both works, but in original .html file fiddle will not work in chrome.(Details )

https://davidwalsh.name/demo/notifications-api.php (Working demo)

There are many free(paid) plugins avaialble on the internet.

  1. Pusher
  2. https://framework.realtime.co/demo/web-push/
1
At:- 12/25/2017 12:56:40 PM Updated at:- 12/25/2017 1:07:21 PM





Login/Register to answer
Or
Register directly by posting answer/details

Full Name *

Email *




By posting your answer you agree on privacy policy & terms of use