What has happened so far, in JavaScript, In 2011?

8:22 PM Xun 2 Comments

In the mere sense of numbers, 12/31/2011 is probably not that different from 1/1/2012. But we are humans. And we humans like to ascribe meaning to everything, especially at the beginning and the end of everything. At the end and the beginning of every year, we like to create reviews and make resolutions, reflect on the past and gaze into the future.

So in this reflective mood, I look back to see what has happened and has been happening with JavaScript, in the year of 2011.

Html5 and CSS3

Image from http://feedgrids.com/originals/post/building-a-better-website-with-html5-css3/

Ah, Html5 and CSS3 are still raging fire. Html5 is nothing new, nor is CSS3. Nor are they becoming official or the standard of the day. Both had been in the working for years and as of now are still under development. Neither are radical departure from their predecessors. Rather, HTML5 builds upon the previous versions of HTML, 4, 3, 2 and 1. It aims to provide web with easier and standardized delivery of multimedia, make our web a natural canvas for everything graphical and animated; CSS3 also aims to enhance the web as the most impressive presentation form, allow things more visually pleasant and effective and yet less burden on developers and designers, thus round corners, box shadows, pretty borders and damn good-looking menus with nothing more than some CSS3.

Yet without JavaScript, Html5 and Css3 are pretty much just some more tags and decorations, they can hardly, if ever, render awe and wonder and the sensation of a live web. For example, check out the follow app that uses graphics libraries like WebGL that in its core are a JavaScript library that made 3D graphics alive in a browser without any plug-ins.

Brain Surface and Tractography Viewer


While JavaScript and all of its siblings such as JScript, ActionScript are really ECMA script in implementation, ECMA script has always sounded wierd, like ""ECMAScript was always an unwanted trade name that sounds like a skin disease (aka ECZEMA)." (Wiki ECMAScript.)

As JavaScript is as thriving as the web, ECMAScript is also working hard on its new project code-named "Harmony", on the helm of publishing its fifth edition in June 2011. The goal for Harmony is to make JavaScript a better language ((yeah, how many people still say with reason that JavaScript sucks) for writing complex applications and libraries, more testable and more modular, more inter-operable, adopting de facto standards where possible, that is, do not throw your granddaddy under the bus even though sometimes he behaves like an old fool.



Like the ECMAScript folks and the rest of JavaScript community, Google too has a lot of strong opinions about the state and future of JavaScript. In October 2011, Google unveiled a new web programming language named "Dart" while vented their frustration with JavaScript through a leaked and now widely read memo at Github. The memo reads:

Javascript has fundamental flaws that cannot be fixed merely by evolving the language. We'll adopt a two-pronged strategy for the future of Javascript. That is: a) keeping harmony with ECMAScript Harmony; b) develop Dart and push Dart to eventually become an open standard and be adopted by web developers and all modern browsers.

So far, all modern browsers (excluding Chrome, of course): IE, Firefox and Safari have declined to adopt Dart. However, whether Dart would win the battle is anybody's guess.


In 2011, everyone has said one thing or two about Node.js, quite a number of projects, applications and companies have adopted Node.js. What is Node.js? What is it for or not for?

Image from http://habrahabr.ru/blogs/webdev/108241/

"Node.js is a platform built on Chrome's JavaScript runtime for easily building fast, scalable network applications. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices."


node.js is not really a JavaScript, but it has the look and feel of JavaScript. In fact, node.js deliberately adopted JavaScript's syntax to ease the pain of learning yet another framework/language/whatever and to make the server and client side script work with less friction.

It also uses the same catchphrases that we use to describe how great JavaScript is: event-driven, asynchronous. Yet, node.js is true, or more true, to these claims. On the web, JavaScript does not drive, what drives are web servers, IIS, Apache. Web servers serves an ever-increasing and crushing amount of traffic and requests by threading, thread this to fetch data, thread that to get a file. Yet there is a limit as to how many threads that a server can generate, and threaded IO is not non-blocking (how long you have to wait behind 6 people for your doctor?). So node.js aims to solve the problem. Why wait? Let's serve you as soon as you come. Let's just create as many connections (web servers) simultaneously, sending and taking care of many mini-requests as soon as possible. node.js accomplishes this by dealing directly with web sockets and using closures for non-blocking.

node.js has made a splash. node.js needs bigger players (as big as twitter, as fast and furious as twitter) to flex its muscles. For linus and mac users, you are ready to play with node.js to check out its potential. For windows, hold on a minute or a year.

JavaScript Frameworks for Mobile
If you noticed how hot All Is (IPhone, IPad, etc.) is, or how busy all Androids are (Google just offer free android development classes), you surely know all the sweet spots for development for mobile. JavaScript has geared for and gravitated towards mobile. There are oh so many JavaScript frameworks now for mobile that can deftly provide responsible and touchable and mobile solutions. JQuery mobile is by far the most popular, the other ones are MooTools mobile, Jo.

Source:JavaScript Frameworks for Mobile


XSS: Cross Site Scripting attack

9:30 AM Xun 1 Comments

XSS (Cross Site Scripting), now and then

In Nov., users of Facebook were "offered an opportunity for something (a shocking must-see video? a free iphone?)" if they could copy and paste a line into their address bar. A number of them did, they were then bombarded with explicit and violent content. For 24 hours, the content spread throughout the site and forced Facebook shut down malicious pages, and roll back any infected user accounts.

Facebook is a fertile ground for XSS infestation. It is only a surprise how blatant and "old timer" the manner of the attack (Yes, free iPhone!). Only in May, Facebook rolled out a "Self-XSS protection" security feature to protect users from such spam and scam, on the wake of three consecutive XSS attacks.

The first was passed as stories posted on users' wall, with a bit of iframe code embeded.

The second one affected a Facebook "channel" page used for session management, also a bit of JavaScript is injected into the url.

The third one involves a video posted through a Facebook app. To unsuspecting eyes, the video is nothing unusual. However, launch of the video also quietly unleashed the coded attack behind. Code screenshot shown below:

Source: Recent Facebook XSS Attacks Show Increasing Sophistication

As a matter of fact, Facebook is faced with clickjacking and scam campaign on a daily basis.

More and more, with ever faster pace, we are willingly / unwillingly make ourselves part of corporate data, for better or for worse. Every tidbit information about ourselves, significant or trivial, name, addresses, phone number, social security numbers, credit card, our friends' names, are fed, mined, aggregated into advertisers' database. Anything we do not directly type into some websites are inferred, stored and updated in the corporate databases too. The explosion of online activities and information means many things. It makes Facebook the crown jewel of social networks, it also subjects Facebook to intense scrutiny and daily attack. It crowns JavaScript the language of the web, it also turns JavaScript into the most widespead tool of malicious scripting.

In 2005, MySpace was about as popular as Facebook is today, and XSS attacks were as little known as it is widespread today. Then in Dec 2005, the security world is awoken to worm named "Samy". The samy worm was designed to spread from one user profile to another, and it infected more than a million users in 24 hours. As potent as it was, the Samy worm was set out to make a name. So it did. It made a lasting impact, the reasearch into xss attacks exploded, unfortunately so did the effort in exploit web vulnerability in the form of XSS attacks.

In 2006, XSS attacks got inventive. Intranat hacks, keystroke tracks, JavaScript port scanners, traojan horses, etc. were disguised in every form that contains some html / javascript code, emails, websites, chat rooms, message board. Security holes were discovered in more than 70% of web sites.

Fast forward to today. In early 2011, IMB published a white paper reporting on their research of XSS attacks. The research used a sample group of about 675 websites, most of them Fortune 500 companies. The method used is a non-intrusive, shallow crawling of the sites involved. Therefore no logins, no deep digging into sites.

The result is disturbing: 14 percent of the sites, through their own or third part JavaScript vulnerabilities, could Infect with Malware and viruses, Perform Phishing attacks on users of these sites, spoof web contents, hijack users' web sessions and perform action on their behalf. The likelihood that a random page on the internet contains a client-side JavaScript vulnerability is approximately one in 55.

(Source: Close encounters of the third kind).

The route of XSS attack

Attacks may come blantantly or stealthily. If your browser is popping up blinking ads saying you are a jackpot winner;if you were unexpectedly led to violent, sextual content while browsing news, you can correctly assume that you are XSS'd; Or you could be completely blindsided until one day your bank told me that your information may have been stolen (this has happened to me).

How did these attacks happen? You may come up with a list of maybe answers. Maybe one day you opened up an email, which led to a suspicious website; or maybe you opened an attachment you thought it was sent from your friend; or maybe you followed the link in the posts on your friend's wall, through your smart phone, your mobile tablet ... One way or another, it is either that: a) you were led to visit a malicious website; or b) you visited a trusted site yet the site was hijacked and was planted a seed of malicious attack; or c) you clicked a link that is crafted with malicious script; d) a security hole of your browser was exploited and javascript was injected.

Elementary XSS details

The chase never ends. You plug one hole, more comes up. XSS is filled with new ways of vulnerability exploitation and code injection. However, something fundamental remains.

There are two major flavors of XSS: non-persistent and persistent. Non-persistent attack happens when a url or form is injected with malicious code, however it is not persistent, it is click-based/event based; Persistent attacks are conceivebally more dangerous, they can cause lasting damage because the code is stored as a cookie or in database by the website, and affect all users who visit the site. In this case, users are defenseless. Outside of the persistent/non persistent categorization, domain-based attacks, which can be both persistent and nonpersistent, are also prevalent. Domain-based attacks are exclusively on the client side and are engineered to exploit vulnerabilities in the html document (script, DOM handling). The vulnerability could be both from the javascript implementation or browser interpretation.

XSS through urls

Script injection frequently happens on the url level. It is first made well known by the security expert Amit Kleint in DOM Based Cross Site Scripting or XSS of the Third Kind

It is a common pratice that we embed bits and pieces of information in the querystirng of an url then parse it in the JavaScript and do something accordingly. As in the example listed by Amit Kleint.

However this serves an opening for code injection for hackers. They can simply call a url as such:

As now most developers are aware of danger of this, hackers are also more skillful disguising their intent. So the above url will be more likely look like below:

(Notes: To my great surprise and annoyance, both of the above url calls execute immediately in blogger. I had to take screenshot of the code. Below is the screenshot of the script gets executed in blogger:)

XSS through input forms

Data can be passed through urls. It also frequently passed through input forms, through input textboxes, textareas. Search boxes were and still are hackers' first bait. They often execute scripts that automatically submit a form and test for opportunities. If a search for "blah" returns a page that says "Sorry, a search for blah is not found", they could then subsitute the "blah" with a test script:
; if the page excuted with a alert box, bingo, they can plan their atrack right now; if no, they can inspect the JavaScript cleansing machanism, then circumvent it.

As a matter of fact, because of the danger of inputting malicious code, many websites use stricter user input validation and output sanitation, encoding and escaping special characters. As a result, hackers also have camouflaged their scripts by playing with quotes, different encoding method.

The Web Application Hacker's Handbook: Finding and Exploiting Security Flaws

XSS through images, flash, pdf, videos. You name it.

On the internet, every object can become a source of script embedding, images, flash objects, pdfs, videos, you name it! And unless you disable JavaScript, script can be excuted upon the event of loading, unloading, or when you thought you were merely watching an harmless video, as in the case of Facebook users in April.

Modern email programs, such as GMail, outlook, normally do not block images from displaying unless your explicitly set permission. Why? Because, the src property of images can either be direct injected with script, or indirectly linked to a malicious site.

Flash object too. Adobe just released a Flash Player update in response to reports that a cross-site scripting vulnerability is being exploited in the wild in active targeted attacks. (Source: Hackers exploiting Flash Player XSS vulnerability

Parting words

There is more, so much more, to talk about XSS, even just to scratch the surface. Blunt forced XSS, XSS filter and evasion, XSS detection and prevention, etc. And it is constantly evolving, the attacking and defending side of XSS. We can say nothing for sure, other than that, XSS is a clear and present and ever-escalating danger, just look at Facebook today.

XSS Attacks: Cross Site Scripting Exploits and Defense


JavaScript prototype

1:21 PM Xun 1 Comments

I must confess: for the longest time, I did not know anything about JavaScript prototype, nor did I care. I was just programming my way in blissful ignorance, however the frequent talk of and reference to JavaScript prototype finally got me.

Turned out prototype is so fundamental to JavaScript that not knowing about it makes you de-facto handicapped, at least when you go deeper and deeper in the rabbit hole that is JavaScript.

What is prototype? As the term implies, it is a model or process to be replicated or learn from.
From (Wiki: Prototype)

Everything, every product has a prototype. Every car has a prototype, every car built from the prototype automatically inherits the functions from the prototype; Every JavaScript object has a set of prototypal properties and methods, every instance of the object carries on the prototypal properties and methods by default. An array has prototypal methods such as
; A string has a different set of methods for string manipulation such as

How do you inspect the prototype of an object?

For objects, you can use
in most modern browsers (IE 9 and above, Chrome, FF); Or simply
in non-IE browsers for both objects and other JavaScript primitive data types.

var a = {};
var pa = Object.getPrototypeOf(a);
console.log(pa); // Object

var b = [];
var pb = Object.getPrototypeOf(b);
console.log(pb); //Array

var c = "I am a string.";
var pc = c.__proto__;
console.log(pc); // String

//custom object
var Person = function (name) {
this.name = name;
this.sayName = function () {
console.log (this.name);

var peter = new Person("peter");
var pp = Object.getPrototypeOf(peter);
console.log(pp); // Object

Alter the prototypal landscape

JavaScript prototype is a powerful thing because it dedicates the genetic make-up of all of its instances and decendants; it is also amazingly meallable, open to alteration and manipulation.

Take the above
constructor for example. The
's prototype is an Object, therefore any
, in our dummy case
, is pre-loaded with all the methods defined in an object prototype, including
. Therefore peter not only can call its local method sayName, it can also check out the methods in its prototype chain

peter.sayName(); // peter
peter.toString(); // Object
peter.toLocalString(); // Object

How does peter knows there is a
method without defining it? Here comes in the concept: prototype chain. What does that mean? It refers the chain of look-ups, the route of upward searching in JavaScript. When a method or a property is called, JavaScript starts searching locally, if find it, great! Execute and return!; if no, one step further, it goes to the prototype of the current object; if still no? It reaches further. So it goes, until it reaches the root of the chain.

A prototype chain is illustrated from the image.


1. JavaScript starts the search with object "a".

2. If no, JavaScript then visits "A.prototype" (the prototype of object "a") and looks for the property.

3. If still no, JavaScript then check "B.prototype" (the prototype of "A") and finds the property. This process of visiting each object's prototype continues until JavaScript reaches the root prototype. This series of links by prototype is called the "prototype chain".

Image and description from Document Object Model Prototypes, Part 1: Introduction

As for the
method for
, you can see the path of search here:

(Prototype chain is the base of JavaScript chaining, exemplified by jQuery; Prototypal chain has some performance implications. The deeper the root is, the deeper the search goes, the heavier performance penalty is, but that is a topic merits an article of its own.)

Back to the
constructor, it defines a method
. And now every instance of Person has its copy of
method. This in itself is a bit of expensive, especially if you have a very complicated
method; in contrast, make it part of the prototypes makes it more memory efficient. To do so, we get rid of the
method in the constructor, and add it to the prototypal arsensal:

var Person = function(name){
this.Name = name;

Person.prototype.sayName = function(){

var mary = new Person("mary");
mary.sayName(); // mary

This is prototypal inheritance in its simpliest form. And we just successfully changed the prototype of the object

If we can make methods part of the prototype, so we can make properties. This can be quite useful if you want to set up some default properties for the object.

var Person = function(name){
this.Name = name;

Person.prototype.sayName = function(){

Person.prototype.canTalk = true;

var mary = new PersonP("mary");
mary.sayName(); // mary
console.log(mary.canTalk); // true

JavaScript built-in objects

All the above deals with a dummy customized object. However, it does not mean you cannot add prototypal methods with JavaScript built-in objects, such as
, such as
is a usual suspect, because people like to manipulate Dates.

For example,

Date.prototype.isAprilFool = function(){
return (this.getMonth() == 3 && this.getDate() == 1)

From Date prototype is april fool

Now you have the IsAprilFool judgement call.

var today = new Date();
today.isAprilFool(); // false


JavaScript inheritance

Javascript inheritance has many forms in subtle or unsubtle variations. It is the topic of constant and ongoing debates. Nearly all forms of JavaScript inheritance are careful studies of JavaScript prototypes, be it classical or peudo-classical or prototypal inheritance.

Mr. Crockford started with classical, and had written about it in Classical Inheritance in JavaScript, then he is convinced with the superiority of prototypal inheritance, and wrote it at here:Prototypal Inheritance in JavaScript. A lot of other people also have produced beautiful articles even libraries with their own version of extend or inherit, for example, John Resig's Simple JavaScript Inheritance and Defining classes and inheritance from the Prototype JavaScript framework.

But it is late now, I already used up my lunch time plus some other time that is slotted for my work. So, so long.


The prototype object of JavaScript
Understanding JavaScript Prototypes.


JavaScript: some good books

11:20 AM Xun 1 Comments

Even within the highly concentrated little world of JavaScript, the amount of information and knowledge can be overwhelming. And they rush to you in every kind of media: books, blogs, online articles, video presentations, websites that dedicated to collect more source code than you can ever possibly read or even browse through. If you were like me, you probably would just jump from page to page, led by the guiding hand of google, then get lost from traveling along the circulous, endless-branching, criss-crossing paths.

At times like this, books may offer you an anchor. If you are patient enough, good books may even offer you great many ah-ha moments, cystal clear insights into concepts that were murky and clouded by competing, half-baked opinions on the web.

With regards to JavaScript, the following books are on my list of good books:

JavaScript: The Good Parts
by Doug Crockford

Available on amazon. However you can also read free here.

Crockford is an eloquant speaker and writer. His insight and keen observation made it possible for him to "discover" the gold of object literal notation (JSON) in its flexibility of representing any structure in simple, succinct and accessible manner.

In JavaScript: The Good Parts, Crockford presents JavaScript's blunders or things that meant for good, however went bad through entrenched bad practices; yet through evil and less ideal, he illustrates how effective, dynamic and liberating and expressive JavaScript can be. Where Java Applet fails, JavaScript shines and wins as the language of the web. Crockford also gave a series of talks surrounding the goodness and badness of JavaScript. All of the videos can be found, you know, at YouTube.

Pro JavaScript Techniques
by John Resig

John Resig is the number one celebrity of the community. Young, penetratingly smart, he created jQuery. He aslo rolled out a bunch of books mostly about JQuery. This Pro JavaScript Techniques however is not JQuery specific, it addresses a wide range of best practices and advanced techniques, such as object-oriented JavaScript, testing and debugging, unobustrusive JavaScript, etc., then he illustrates his techniques with sophisticated real life examples, auto-complete search, image gallaries, an ajax wiki. I am sure the moment you put down the book, you will be able to put together a dazzling web site.

High Performance JavaScript
by Nicholas C. Zakas

Nicholas C. Zakas is also a highly recongnizable name. He is the principal front end engineer for Yahoo! He has authored accaimled JavaScript book Professional JavaScript for web developers and co-authored Professional Ajax. Nicholas also frequently speaks in various venus.

About the book. Fast, better, responsive web is forever the goal for any websites. With JavaScript growing in complexity and size, optimization through better coding, better DOM handling, code minimalization are more important than ever. So in the book: High Performance JavaScript, Nicolas illustrates various techniques, do-s and dont-s, to speed up page loading and eliminate performance bottlenecks. Rather than just saying you need to do this and that, he also back up his case by showing various performance metrics among different browsers.

Professional JavaScript for web developers
by Nicholas C. Zakas

The book features a very handsome Nicholas C. Zakas on the cover, which, in short order, is followed by a forward that succinctly yet beatifully captures the trajectory of JavaScript, and continues on to offer a glowing Why Nicholas' book is such a great book. Quotes blow:

"What Zakas accomplished with Professional JavaScript for Web Developers is singular: he treated JavaScript as a subject that is both serious and accessible. If you are a programmer, you will learn where JavaScript fits into the broader spectrum of languages and paradigms with which you're farmiliar. You'll learn how its sytem of inheritance and its intrinsic dynamism are, yes, unconventional but also liberating and powerful."

Pro JavaScript Design Patterns
by Ross Harmes, Dustin Diaz

Published in 2008, this book could be a little out dated to your taste. However, you can read to your heart's content to soak in all of the object-oriented patterns, and how can you apply those in JavaScript in real life examples. And if you are to design a complex JavaScript application, it is probably a good idea to think through your structure through the lens of those object-oriented design patterns.

JavaScript: The Definitive Guide
by David Flanagan

From the first edition in 1996, to the six edition in 2011, JavaScript: The Definitive Guide certainly passed the test of longetivity. It also says its enduring appeal to programmers, either novices or professionals. With each edition, the book shed some out-dated concepts and incorporates some new standards and pratices, which is great. I am sure The Definitive Guide is going to live for as long as JavaScript lives.

Oh, boy, the definitive guide is bulky, however it has very straight-forward structure: Core JavaScript, meant to be a JavaScript language reference, to me it can be a quick cheat sheet; Client Side javascript, gets into the implemenation business, JavaScript in action. To me, the first part is more valuable. The second part comes across as a little too simplistic or inadequate.