Dynamic Favicons using HTML5 Local Storage and TinyCon
I was perusing Github the other day and I came across this awesome little JavaScript library. It's called TinyCon and it's a small library for manipulating the favicon in your browser. It adds alert bubbles and changing images pretty similar to the way Gmail does.
It's basically a really fun little library that allows you to add a notification bubble to your favicons. I started to play around with the code provided on Github and got up and running in no time.
Using this simple example will give you something like this:
As you can see the above example is really simple and not really real world. It's using a timer to update the icon every second. After messing around with the example on the site, I wondered how I could apply the notifications to this site. If I checked the last blog entry that they read on this site, then I would be able to notify them if there were any new blog post's since their last visit. It's just a fun experiment really!
If you are a regular visitor to the site, you might notice that you have a notification next to the favicon. This is how I went about it.
This site is coded using MVC2 so I added a new variable on my Controller to the TempData called "TotalPageCount". This is then added to a hidden field on the page that I can use to read the value from.
Next, I am adding a quick check to see if the user's browser will be able to cope with HTML5 Local Storage. If they are able to use it, I check if they have visited before and if so compare it with the previous value (to check for any updates). If there are any new blog posts since their last visit then I simple use TinyCon and add a notification to the favicon. I am no great JavaScript master, so please forgive me if you spot any better ways of achieving the same goal in the code!
Oh, there is also a gotcha when dealing with dynamic favicons. I started running through the example on the TinyCon site and came across this error when debugging:
It took me a while to solve this, but thanks to this post on StackOverflow I managed to solve it. Basically, you need to have the favicon in your own domain or it will cause a security exception. Once that is in place, you should be able to get up running without any problems.
If the browser doesn't support dynamic favicons, it will gracefully fall back and update the title with a number instead. This blog post is really a bit of fun, but I can see a load of uses for the helpful little library.