October 13, 2015 7:57 am

Creating a HTML5 app that shows gags in real-time Part 2

The Notifications API (Web Notifications) is currently supported by 60.67% of web users globally according to Can I Use.

Creating a HTML5 app that shows gags in real-time 1

  • Firefox 38+ supports it fully
  • Chrome 31+ supports it fully
  • Safari 8+ supports it fully
  • Opera 31+ supports it in entirety
  • IE does not support it
  • The new Edge browser currently does not support it.
  • The Android’s native browser does not support it at this moment.

To use it, we first check if the user’s browser supports the API with:

Then, we check if the user already has granted our website permission to post notifications to him:

However, we may not have been granted permission yet but if the user has not denied us permission and we do not have permission – this means that we should ask for permission and if he grants us the permission afterwards, we can again send him a notification.

If the user does not support desktop notifications, the least we can do is inform him the app has a functionality which he cannot use:

Here is how our notification function looks like in its entirety:

It can be seen that the function has a single parameter – the number of new gags which we pass to the craftNotification function.

The function mentioned above instantiates a new notification using the new Notification constructor which takes two parameters – a title and an options object.

A widely used property of the options is body which holds the body (the message) of the notification. However, we would not be needing that as the title is enough to inform the user of new gags. Though we will be using another property – icon – which takes a URL or a path to an image which will appear alongside the notification.

Here is how the function which makes notifications looks like:

You can see we are utilizing the number of new gags given by the Worker and informing the user of the new gags. We are also determining whether we should use the word gag or gags (plural) depending on the number of new gags.

Author Ivan Dimov

Ivan is a student of IT, a freelance web designer/developer and a tech writer. He deals with both front-end and back-end stuff. Whenever he is not in front of an Internet-enabled device he is probably reading a book or traveling. You can find more about him at: http://www.dimoff.biz. facebook, twitter

Tutorial Categories: