‘Realtime’ Chat with WebSocket and NodeJS

Update (2017): This post is outdated and shite. Please look elsewhere for better examples of similar apps. If you insist on seeing the naive code I wrote for the demo, there is a github link in the post.

DEMO (link removed)

(Open the chat in two or more browser windows/computers and check how fast the realtime updation is!)

Gmail chat, Facebook chat etc were implemented using a technique – rather a hack – called long polling[1]. It is the technique where the client initiates a request to the server. The server rather than returning the client with a response, keeps the connection open for a longer time. The server only returns to the client with a response when it (server) has something new for the client. The advantage of long polling over normal polling are reduced latency and saving from the overhead of sending too many short http requests. Continue Reading


Web service API Specification Doc Template

Finally I got sick with the webservice spec documents we were using at my previous employer. I searched all over the web for a document template that I could use for laying out our new web service’s API specification. I found several ones – good and bad -, but none were up to my expectations. So I decided to create a document template myself. My key design goals were the following:-

  • Ease of use
  • Clear
  • Concise
  • Not boring to look at.

I finally came up with a document template that I (and my colleagues) liked. Hope you find it useful too. Its created in Google Docs and shared ‘publicly’, so you can easily copy it and use it for your own projects.

See it in action -> Web service API Specification Document Template

 

Click here to use the template

(To use the template, make sure you are logged into your Google/Gmail account and click the above link. You should see a ‘Use this template’ button on the right top corner of the page.)

Tips for use:-

  1. Be consistent
  2. Use colors, fonts, font size etc to visually distinguish and classify things.
  3. Use fixed width fonts (courier, monospace etc) for showing code.
  4. Don’t clutter it up with too many colors and fonts.
  5. Managing and updating a good document is not very easy; but remember, everything worth doing is difficult anyway!

So what do you think? Like it? Where do I need to improve it?


New Year Resolutions

New year is here and crazy people all over the world are busy making new year resolutions that they know they will stop following just a few days into the new year. Yet here is another stupid guy’s new year resolutions – as a humble tribute to all those out there crazy enough to take unrealistic decisions and follow their crazy minds.

Below are my “resolutions” for the year ahead.

1. Do at least one good thing a day.

2. Publish a blog post at least once every two weeks.

3. (and here is the usual -> ) Of course, start working out 😀

4. Do more stuff outside of the computer. Carpe diem.

Update (Feb 2013): Yeah, yeah, yeah.. Nothing worked (as usual) :p


How to geek up your web server

A screenshot of my development server

I dislike default. Default is easy, and will always work. But accept it, default is boring.

Let’s see how to spice up your web server a little bit. If you want to see how our server is going to look like after we make the changes, click the demo link below.

Demo ~ Download Source

Basically what we are going to do is to add a Header file and a ReadMe file for our directory listing page. The header file is a text file that is rendered above the content list in a directory and ReadMe is displayed at the bottom. To add the Header and ReadMe, do the following:-

 

1. Open your httpd.conf file

The httpd.conf file is usually located in the /etc/apache2 directory. Open this file, or open your virtual hosts file (usually a file called 000-default) located inside /etc/apache2/sites-enabled/

2. You should see a lot of stuff like the following:-

DocumentRoot /home/Dev/Server
<Directory />
    Options FollowSymLinks
    AllowOverride All
</Directory>

<Directory /home/Dev/Server>
    Options Indexes FollowSymLinks MultiViews
    AllowOverride All
    Order allow,deny
    allow from all
</Directory>

3. Find your virtual host

(the folder where your website files are stored) and add the following two directives there.

    HeaderName /.ServerFiles/HEADER.html
    ReadmeName /.ServerFiles/NOTICE.html

.ServerFiles is a folder inside my webserver root. Notice the “.” (dot) in front of the folder name. As you know, files and folders starting with “.” are hidden in Linux.

So I just created a hidden folder inside my webserver root folder and added two files html files in it HEADER.html and NOTICE.html.

 

After adding the Header and ReadMe directives, my host defenition looks like this:-

<Directory /home/Dev/Server>
    Options Indexes FollowSymLinks MultiViews
    AllowOverride All
    Order allow,deny
    allow from all
    HeaderName /.ServerFiles/HEADER.html 
    ReadmeName /.ServerFiles/NOTICE.html
</Directory>

4. And add Header and ReadMe to style your server!

You can download and use the Header and ReadMe file I’m using here or see how the server will look like if you use my Header and ReadMe.

 

You can use pretty much any kind of HTML, CSS and Javascript in these files. You can even load jQuery there and do some of that pretty fancy effects there. However, try to keep it light.


Facebook Like Automatic Content Loading on Scrolling

We have all seen the automatic content loading used in Facebook. Let’s see how easily it can be implemented using jQuery.

View Demo

What we do to achieve this is whenever a scroll event is fired, check if we have reached the bottom of the page, and if we are at the bottom, call our ajax function to load the content.

 

$(document).scroll(function(){
    if ($(window).scrollTop() + $(window).height() == $(document).height()) {
        // Reached page bottom. Call the ajax function or any other foo here.
    }
});

 

.scroll() is fired every time the user scrolls the page.
$(window).scrollTop() returns the number of pixels hidden ‘above’ when the page is scrolled.
$(window).height() gives the height of the window. Same as window.innerHeight
$(document).height() gives the total height of the page.

Well, that’s that. Cool, right?

Facebook content Loading

Automatic Content Loading in Facebook


Do You Love Me?

Hey, today is 31st December. So i guess this is my last post of the century, or watever. Here is a little treat for ya to geek with friends.

Just copy paste the below code into your browser’s url bar and hit enter.

javascript:function checkLove(love){if (love)alert("He he he, cool!");else{if(love != undefined) alert("Sorry, you must love me.");checkLove(confirm("Do you love me?"));}}checkLove();

So, wishing a crazy new yr for all f u.


The Making of a jQuery Plugin

Hi folks, today we are going to write a simple, yet useful jQuery plugin. The plugin we write is named The jQuery Placeholder plugin.

The problem:- A very useful feature that was introduced in HTML5 was the ‘placeholder’ attribute [W3C Spec] for forms. The placeholder attribute lets us specify a default value for textfields (and other form elements). The default value/placeholder text will be shown if the user hasn’t entered a value in the textfield. Sounds handy right? But the problem is that as HTML 5 is not widely supported, only few browsers support the placeholder attribute currently. (As you could imagine, Internet Explorer doesn’t support, yet.)

Our goal:- Simulate the placeholder effect in older browsers that don’t support HTML5 placeholders and if the browser supports placeholder attribute, then fall back and use the native support instead.

HTML5 Placeholder Effect

And the fun part:- We are writing a jQuery plugin to do that 🙂

In this post, we are going to implement the basic functionality and later we will look at progressively enhancing our plugin.

Before We Start

Demo of what we are going to write.

You can write your plugin code inside a text file and save it as file-name.js. But try sticking to the convention ‘jquery.pluginName.js’ when naming your plugin file. So we are going to save our placeholder plugin code in a file known as jquery.placeholder.js

 

Step 1: Laying The Foundation

Let us lay the foundation of our jQuery plugin. Once the foundation is laid, we can build our plugin over it easily.

 

Every jQuery plugin is added as a property of the jQuery.fn object. The name of the property is the name of our plugin.

$.fn.placeholder = function() {

    // plugin code goes here

}

If you didn’t know already, $ is a shortcut to the jQuery object. In your script it is the same to use  ‘jQuery‘ or just the ‘$’ sign. But $ sign might collide with other code or libraries used in the same page, so, as the jQuery Plugin authoring documentation recommends, it is better to use the name ‘jQuery‘ itself or explicitly assign the jQuery object to the $ symbol within the context of our plugin code as follows:-

(function($) {
  $.fn.placeholder = function() {

    // plugin code goes here

  };
})(jQuery);

That was it. We  have laid the foundation. Now within out plugin function, $ will always refer to the jQuery object.

Now all we need to do is to add our plugin code to the foundation. You can invoke your plugin code on any element in your web page by calling the plugin method like this:-

<script type="text/javascript">
   $(document).ready(function() {     $('input').placeholder(); });

   /* Only $('input').placeholder() is needed to invoke your plugin.
    But leaving out $(document).ready() might give you unexpected results. */
</script>

Step 2: Writing the functional code of our plugin

I have divided the functional code into 3 parts:-

Step 2.1 – Show the placeholder text inside the textbox when the page is loaded

// Getting the value specified for the currently selected elements 'placeholder' attribute
var placeholderText = this.attr('placeholder');

if (this.val() == '') {
    this.val(placeholderText);
}

The code is self explanatory. We fetch the placeholder text specified for the selected element and assign it to the variable placeholderText. For this we use the .attr() method, which returns the value of the specified attribute.

Then we are checking whether the text field is empty. If the text field is empty, set the previously fetched placeholder text as the value of the element. For both of this (checking and setting), we are using the jQuery method .val() which can get or set the ‘value’ property of any element that has a ‘value’ attribute.

Oh by the way, have you noticed that we are using just this instead of the usual $(this) that we usually use in our code. This is because, inside the immediate scope plugin function this itself refers to the jQuery object of the element it is invoked on. No need to wrap this inside $(). Don’t worry if it sounds fishy. We will soon see when to use $(this) instead of this.

Now the following text field will show the text ‘Name’ in it when the page is loaded.

Our textbox will appear like this in older browsers.Textbox with placeholder attributre.

 

Step 2.2 – Hide the default (placeholder) text when the user clicks inside the textbox

Now when somebody clicks inside the textbox, we need the placeholder text to be hidden. The following code will do that.

this.click(function() {
    // when someone clicks inside the text field, check if the user had
    // entered anything inside the text box OR changed the default text.
    // If the user hadn't entered anything, clear the textbox.
    if ($(this).val() == placeholderText) {
        $(this).val('');
    }
});

You might have noticed that now we are using $(this) instead of just this. This is because, when inside callback functions, just using this will not refer to the jQuery object, we have to use $(this) to refer to the jQuery object. In this case we are using $(this) inside the callback function of the click method. (SPOILER: When a function is passed as an argument to another function, the passed function is called the callback function.)

Step 2.3 – Restore the placeholder text when the user clicks outside the textbox

Next we need to restore the placeholder text when the user clicks outside of the textbox (a.k.a when the textbox loses focus or is blurred, when said in technical terms, duh!)

this.blur(function() {
    // If the textbox is empty, restore the placeholder text
    if ($(this).val() == '') {
        $(this).val(placeholderText);
    }
});

That was it!! Now your plugin will show placeholder text even in older browsers (read Internet Explorer and the sort). But modern browsers like Firefox (3.7+) and Chrome/Safari (4.0+) supports HTML5 placeholder attribute natively. So in such cases, it is better to make our plugin code fall back and use the browser’s native placeholder support instead.

Step 3: If the browser natively supports HTML5 placeholder attribute, use it instead of our plugin code.

Ok, this step is easy.

var input = document.createElement('input');
if ('placeholder' in input) {
    return this;
}

Add the above code as the first thing inside your plugin foundation. The code checks if the browser supports placeholder attribute for ‘input’ elements (<input type=” ” />). If the browser supports placeholder, we immediately exit from the placeholder function using the return statement. Note that we are returning this instead of just return; or return true; or anything like that. We did it because jQuery recommends we always return this when exiting our plugin code (This is to maintain a cool feature of jQuery known as chainability). So dont forget to add a return this; at the end of our plugin code too.

Browsers showing placeholder text

What is Next?
We have implemented a plugin with the bare minimum features. (still not bad, okay!). Our plugin has limitations. For example, it won’t work as we intend on password fields or won’t work at all in textareas. In the next post, we will see how we can enhance our plugin to support password fields and textareas and also add some more coolness to our already awesome plugin :).

You can download the full plugin code here.

By the way, did you wonder how I ran both Firefox 9 and 3.6 at the same time?? (Yeah, I did that B-) ). To know how to do that checkout the post How to run multiple Firefox versions at the same time.

Please let me know your questions and suggestions in the comment form below.

Also, if you like the post, please share it with your friends. If you don’t, just share it in Facebook okay ;), so the whole world will know how bad I write.

 


Run multiple Firefox instances/versions at the same time

Here is a quick tip for ya. To run multiple instances of Firefox at the same time, do the following.

Firefox Profile Manager

Linux

1. Run this command in Command Terminal : firefox -p -no-remote

2. The Firefox profile manager will open and ask you to choose the profile you want to use. If you already have more than 1 profile, click on the “Create Profile” button to create a new profile and once the new profile is created, select it and click “Start Firefox”

3. That’s all.

 

Windows

1. Open run prompt by pressing Windows key + R

2. Run this command in run : firefox.exe -P -no-remote (NB: -P is in CAPS)

3. The Firefox profile manager will open and ask you to choose the profile you want to use. If you already have more than 1 profile, click on the “Create Profile” button to create a new profile and once the new profile is created, select it and click “Start Firefox”

4. That’s all.

 

You can also edit the Firefox short cut in your desktop, quick launch (Windows) or panel (Linux) and add the text -p -no-remote to it, so that each time you open Firefox it will ask you to choose the profile you want to load.

 

What is this good for?

1. You can sign into multiple Gmail accounts (or other accounts for that matter) at the same time (One in each Firefox instance)

2. You can run multiple versions of Firefox at the same time. Just create a separate profile for each version and choose the correct profile when opening Firefox.

 

Did it solve a different problem for you? Let others know through the comments below.


13+ Firefox Addons to Improve Your Online Safety and Privacy

[updated: December 2012]

1. TorButton

Complete anonymity is not possible on the internet. Tor is the next best thing available. Tor is one of the best privacy softwares available. Tor is recommended by EFF, who is the biggest advocate of online privacy. TorButton will make it easy to make firefox use Tor. Though it is the best for privacy online, configuring Tor may be a bit of a pain for first timers. If you install Tor, it will install the TorButton Firefox addon also. To download Tor, visit the Tor website.

2. NoScript

If Tor is the king of privacy, then NoScript is the king of security. NoScript protects you by blocking unauthorized sites from running scripts and programs in your computer. NoScript offers protection against cross site scripting attacks, router hacking, click jacking etc. NoScript is very much recommended, no matter you are a newbie or an experienced user.

3. WOT

WOT provides you information regarding websites’ trustworthiness based on ratings provided by a global community of users. Users rate websites based on their experiences, so you can know if you can trust a site before entering it. WOT will warn you about sites with low reputation (read it as dangerous websites) and hence will protect you from scams, phishing sites etc

4. FoxyProxy

Proxies are the easiest means to get basic anonymity on the web. By using a proxy, you can hide your IP address and thereby your exact physical location from the websites you visit. FoxyProxy will make firefox access sites through proxies, hence hiding information about you. FoxyProxy has advanced features and newbies may find it a lil complex. In that case, you can use Proxilla, which is relatively easy to use.

5. BetterPrivacy

The tracking ability of normal cookies is low. So internet marketing and research groups have come up with a more persistent way to track users – Flash Cookies (aka LSO‘s). Flash cookies offer more storage – 100 kb, as opposed to the 4 kb offered by normal cookies – and can’t be removed as easily as normal cookies. An alarmingly large number of websites now use flash cookies to track users. BetterPrivacy can protect you from flash cookies.

6. Roboform Password Manager or Secure Login

It is not safe to use the same password with multiple sites. But keeping track of different complex passwords for different sites is difficult. Here is where password managers come to rescue us. Password managers can store login information securely and can make it easily and securely accessible for us. Roboform password manager offers everything you need – easy access, encrypted storage, form filling etc.

Secure Login is another powerful password manager offering lot of useful features and stuff.

7. Enigform

Enigform protects our data and traffic by digitally signing our HTTP requests (including AJAX calls). The technique used is pretty impressive. It brings OpenPGP signing and encryption to HTTP traffic. Please keep in mind that Enigform can work its magic only if the website you are visiting runs on a mod_openpgp enabled Apache web server.

8. CookieSwap

Are you logged into your email account and some other important websites and need to open a suspicious looking site. Doing that may compromise the your important accounts. Then CookieSwap is for you. This addon will let you switch your firefox’s profile, hence hiding the active cookies. This addon can also be used for signing into multiple gmail/yahoo accounts at the same time. This is a very useful addon which I previously reviewed here among 25 Incredibly Useful and Cool Firefox Addons for Geeks and Web Developers.

9. Ghostery

Every single website you visit is tracking you. They are spying you to know your personal details such as browsing habits, interests and even sexual orientation. With Ghostery, you can see who is tracking can learn more about them, such as their privacy policy etc. Ghostery also makes it easy to block tracking codes and cookies from sites of your choice.

10. Close’n forget

This addon can close the current tab and forget everything about the visit. Close’n forget will delete the cookies, history and every information about that site. (This addon MAY not clear all the data about your visit. Please check if it is working as it should before you try something serious)

11. LongURL

Now we come across shortened links every day in our life. Almost every link posted in twitter and email newsletters are now cloaked by some sort of a URL shortening service. It is really REALLY important to know where a URL is taking you before you click it. One normal looking wrong link can devastate you. The LongURL addon can find where shortened links take you. So be sure before you clink. (This addon don’t work with the latest version of firefox yet)

12. TabRenamizer

People always just love to watch over our shoulders and read the titles of our opened tabs. TabRenamizer is the solution against such prying eyes. With one click, you can rename your tab titles to something more.. serene.

13. Fission

Fission is not exactly a security or privacy addon. But it makes it easy for us to spot the domain name from the URL. Scammes and phishers (bad people) use URL’s closely matching to genuine ones to carry our phishing attacks. They may create a fake gmail login page at some location like www.google.com-accountLogin.some-domain-name.com. Such addresses are easy and inexpensive to create. Unsuspecting users may read only the www.google.com in front of the URL and type in their username and password thinking that it is the legitimate site.

I have stated the importance of taking notice of the address bar in a previous article – 7 Points to Stay Safe in the Social Web.

The Fission addon can highlight the actual root domain, making it easy to recognize fake URL’s. See below how the fake URL is easily spottable with Fission enabled.

So have you used any of these addons? Do you know or recommend any other security/privacy addon? Please share your knowledge with others through the comments.

 

14. HTTPS Everywhere

HTTPS Everywhere is a useful addon developed by the Electronic Frontier Foundation, the leading digital privacy advocacy group. This addon will enable secure connection when you connect to popular websites (if the sites actually support it). A version of this addon for Google Chrome browser also is available at the above link.

 

Lighter Side

Image Source: Geek and Poke


Top 5 Free Antivirus Softwares for Personal Use

Here is the list of the top 5 free anti-virus softwares. The statistics and rankings are collected from all over the web, especially from security related user communities and download sites such as download.com and softpedia. Why spend money when you can get top class virus protection just for free. All of the security softwares reviewed here are as competent as the paid products or even better. Please share your views through comments.

AVG

1. AVG Free

AVG is my favorite anti-virus and I have been using it for almost 5 years now. Not just me, it seems to be the world’s favorite antivirus program. AVG is the most downloaded anti-virus according to CNET’s download.com. AVG is far better than most paid anti-virus programs and is light weight and is less intrusive. AVG has paid versions also, but the free version itself does almost everything a personal user needs. Contains an anti-spyware tool, email scanner link scanner etc.

Avira

2. Avira Free

Avira is my second choice after AVG. The only thing I do not like about Avira is that when it detects something, it displays a warning box each time and produces a beep sound from the CPU buzzer. I personally find it very annoying, but I have a lot of geek and normal friends who have been using Avira for years and would swear on its name.

Avast

3. Avast

Avast is currently the second most popular anti-virus software, kicking Avira from its position. The user interface is very easy and less confusing than that of its previous version. Avast offers good protection also. It has other real-time shields such as anti-spyware.

Microsoft Security Essentials

4. Microsoft Security Essentials

Microsoft Security Essentials is a sleek, light weight utility that requires very little system resources and does its job pretty well. MS Security Essentials runs good even in older systems. The user interface is so easy that even your cat can use it. Unlike the other anti-virus softwares mentioned here, MS Security Essentials do not have a paid version and it is likely to stay free always.

Malwarebytes Anti-Malware

5. Malwarebytes

Malwarebytes Anti-Malware is best when used as a compliment with your regular anti-virus program. Malwarebytes do not run in the background and provide constant protection for your system, but it will come handy when you need a quick virus scan and removal. But realtime protection, scheduled scanning and automatic updates are paid features and not available in the free version.

Have you used these anti-virus programs? Which is your favorite? Share your experience with the fellow readers through comments below.


Pages:1234