Tuesday, 20 March 2018

How to display browser notification in website using javascript

Description : In this post how to display notification in website using javascript. this notfication display if your browser is open or minimized. write below javascript for display browser notfication

Step 1 : add below javascript for notfication display

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Step 2 : add below javascript code for display notfication

<script>
        $(document).ready(function () {

            document.addEventListener('DOMContentLoaded', function () {
                if (Notification.permission !== "granted") {
                    Notification.requestPermission();
                }
            }); 

        });

        function NotifyMe(title, desc, url) {
            if (Notification.permission !== "granted") {
                Notification.requestPermission();
            }
            else {
                var notification = new Notification(title, {
                    icon: url,
                    body: desc,
                });

                /* Remove the notification from Notification Center when clicked.*/
                notification.onclick = function () {
                    window.open(url);
                };

                /* Callback function when the notification is closed. */
                notification.onclose = function () {
                    console.log('Notification closed');
                };
            }
        } 
</script>

Step : Add HTML button if click on button it call function NotfiyMe. here 3 parameter for set dynamic text in notfication 1st is notficiation title, 2nd is description of notficiation and last 3rd is URL for display image in notification

<button onclick="NotifyMe('Browser Notification', 'This is testing browser notification.','https://png.icons8.com/color/260/comedy.png')">Display Notification</button>

- Below screenshot for Notification looks like

No comments:

Post a Comment