October 20, 2016

Browser Notifications

Have you ever wondered how some web pages are able to display pop up notifications outside the browser? I did. And last week I had fun learning about the Javascript Web Notifications API.

The web notifications are really easy to use. And, of course, notifications are even more fun to use from clojurescript.

Browser Support

If the js/Notification object is present, then the browser supports the notification API.

(defn notification-supported? []
  js/Notification)

Notification Permissions

After discovering whether notifications are supported, you can check if they are permitted like this:

(defn notification-permission []
  (.-permission js/Notification))
  
(defn notification-permitted? []
  (= "granted" (notification-permission)))

If notifications haven't been permitted yet, you can ask the user to permit using this snippet. In my case, I update a global data atom with the result:

(defn notification-request-permission! [data path]
  (.requestPermission 
   js/Notification 
   (fn [permission]
     (swap! data assoc-in path {:enabled true
                                :permitted (= "granted" permission)
                                :permission permission}))))

Create Notifications

After you've checked that notifications are supported and permitted, then it's time to create some notifications. Which is also very easy. I also added the option to play a sound as well:

(defn create-notification 
  [enabled? & [{:keys [title body icon sound]
                :or {title ""
                     body  ""
                     icon "/i/clojure-logo.png"}}]]
  (when (and (notification-permitted?) enabled?)
    (let [n (js/Notification. 
             title 
             (clj->js {:body body
                       :icon icon}))]
      (when sound
        (.play (js/Audio. sound)))
      ;;(js/setTimeout #(.close n), 5000)
      n)))

See it in Action

And that's really all there is to it! Here's a Live Demo:

Have fun annoying your end users enriching the user experience with notifications!

Tags: clojure javascript clojurescript