Presentation on HTML5 Security, Part-2 - OWASP Hyd

In continuation my previous talk on HTML5 Security at OWASP Hyd, I have covered few more interesting concepts at OWASP Hyd August meet. Slides are more or less the same as my previous session but it was more demo driven where I've shown known security problems and secure coding practices to be followed while using HTML5. 

I've been committing some of the basic demos whenever I find time into my github account. I shall blog more about some interesting topics very soon.

A note on JSONP & misconceptions of Cross Origin AJAX

Web developers who have worked on accessing APIs using JavaScript would be very much familiar with the term “JSONP”. Many web devs whom I have met offline or in online discussion forums seem to have some misconceptions about JSONP. Below are some of the basic & common definitions which I have come across:

  • JSONP is a technique to work with remote APIs
  • It is nothing but Cross Origin AJAX
  • If we add a query string like “?callback=someCallback” and fire jQuery’s $.ajax or $.getJSON, what we are doing is nothing but a JSONP call.
  • May be a slightly complicated definition: Cross origin AJAX is possible only when the response thrown is JavaScript
  • and many more..

The truth in the above statements is very little and such definitions add more confusion, bringing in misconceptions. In my recent presentation “Content Isolation with Same Origin Policy”, I put up the below slides (check slides 4 & 5 in the ppt)













For all practical purposes, the first one is possible and second one is not. Apart from the tweaked definitions of JSONP as stated above, the below reasoning complicates the topic:

  • In the first case, the content requested is of the type “text/javascript” while in the second case it is HTML. So browsers look at content type of the response header and decide whether they should block the content or not (actually, a very good observation).
  • There is a “?callback=?” parameter in the first case enables jQuery to make the cross origin call in the first case
  • Server side framework should have special capabilities (Iike inbuilt serialization/deserialization) for the first case to work

I thought it would be nice to summarize few facts and hence this post. Read on.

What's an Origin?

The combination of scheme://host:port is what browsers treat as an Origin. e.g.,,, belong to different origins as they differ in one of scheme, host or port. Remember that and are different URLs but not different origins. Also, a domain ( and its subdomain ( belong to different origins (this particular restriction can be relaxed using a technique called domain relaxation, which is out of scope of this topic).

Can my client script read your emails?

Browsers restrict JavaScript calls to server (read as AJAX) based on Origin. This is governed by a policy called Same Origin Policy. In other words, client script in your page can make calls only to your server (strictly speaking, origin). If this rule wasn’t there, it would have been possible to write a script in some arbitrary web page which can read your web based email conversations.

Cross Origin AJAX? Really?

For the reason stated above, a page can make an AJAX call to the same origin from which it originated. If I am allowed to coin an acronym stressing on the boundaries of AJAX, I would coin “AJAX-FOO”, which expands to “Asynchronous JavaScript And XML For Own Origin”. As soon as a new XMLHttpRequest is fired to a remote origin, browsers check the origin of the page with the destination of the request. If both are same, the call is allowed. Else, the call is blocked with an appropriate error message. So there is nothing like Cross Origin AJAX.

Understanding JSONP (TL;DR: It’s all about script tag hack!)

As they say, necessity is the mother of invention. When web2.0 APIs were introduced, they desperately wanted cross origin interactions. JSNOP was discovered as a hack/work-around to bypass the restrictions of Same Origin Policy.

The idea behind it is very simple. Same Origin Policy doesn't apply for scripts (and a couple of other elements too). A <script> tag in a web page can load JavaScript from any origin (i.e., when you embed jQuery.js pointing to a CDN, loading from a remote origin is allowed). Using this loophole, one can create cross origin requests.

Simple example to create your own JSONP service

1. Create a HTML page having two JavaScript files. In script1.js, create a function “processData”

function processData(data){ 
console.log('Hello '+data.firstName+' '+data.lastName);

2. In script2.js execute the above function by passing valid JSON data:

processData({firstName:'Krishna', lastName:'Chaitanya'}); 

3. When you load the page, both the script files load, code in the second file executes the function defined in the first file. This is an expected behavior.

4. Create a file “” (yes, create it with this dummy extension. This is going to be your web service) and place it in the same folder. Open it and write the same code as in step 2. Now open your web server (IIS or your preferable one), go to your site, open mime types section and add a new mime type “.abc” having the mime type value “text/javascript”.

5. Now remove reference to “script2.js” and add a reference to this new file “” in the head section like this:

<script type="text/javascript" src=""></script>

6. When you load the page now, you get the same behavior as that of script2. So far, everything is in the same origin. Place the file “” in another origin (simply create another website on a different port number-recollect that different ports means different origins) and reference it in script tag and the code still works.

What you have done is, you have loaded content from a remote service via script tag injection. This is the essence of JSONP. The idea of having a random file format “.abc” is just to show that any file which can serve script content will hold good for this. You may use your “.aspx”, “.asmx”, “.ashx” or whatever to achieve this.

Hence, JSONP is always a script Injection and has nothing to do with XMLHttpRequest object and AJAX.

How JavaScript libraries like jQuery help (mislead) you

If you use libraries like jQuery, they give you a common syntax which works for AJAX as well as JSONP hack. They do a lot of work behind the screens to make a JSONP script injection

$.getJSON('', function (data) { 

In the above API for Facebook, if the value for callback is given by the developer as “”, facebook returns json data by wrapping it in the function “fetch” (open the link in your browser and check the output. Note: IE will ask to save the response as ".js" file.). If the function name is omitted, jQuery handles it in an interesting/tricky manner. It takes the success callback as the function to be executed (similar to “processData” function as declared above), creates a random function name and assigns the callback to it. The server too responds by wrapping its json data in the random function name which it got from the request (see the first screenshot in this blog post). Once the http transaction is done, jQuery destroys the random function.

(Note: To test the trick jQuery uses, I used burp proxy to intercept and pause the request sent by jQuery. While pausing, I typed jQuery’s random function name in browser’s console and it printed the definition of the function. After the response is received, I did the same and I got that function is undefined. This way I was able to deduce the trick jQuery uses for JSONP).

In this process, jQuery does not fire an AJAX call. All it does is injection of script tag and serving javascript in its response. Since the syntax for AJAX and JSONP are maintained the same, web developers tend to confuse about JSONP.

So what mime-type should be served for a successful JSONP request?

Well, this is a topic of confusion, at least for me. Since the served content is JavaScript, the preferred mime-type should be “application/javascript” or “text/javascript” or may be "application/json". In my demo, I’ve changed the mime type of the above service to “image/gif”, “text/css” etc and the script still worked in all modern browsers without any warnings. Also, there are cases where browsers show a "save file" dialog when wrong mime type is served. Enabling adhoc mime types has security concerns and research is being done in this area for standardizing mime-type. At least for now, “application/javascript” can be used and anyways CORS is the future, so no more content type worries.

Hope the article provided useful info. Share your thoughts or discuss if you see the need for any corrections. Happy coding Smile

HTML5 Sandbox and some notes

While building mashups, one of the primary goals is to securely isolate content coming from different origins. Generally, client side mashups are built in one of the two ways-(1) Embedding third party scripts in a web page (2) Loading remote content via iframes. Embedding scripts provides more interactivity but dilutes security since the scripts run with full privileges and could be malicious. Using iframes reduces interactivity but enhances security since they isolate content via same-origin-policy (Script inside a cross-origin iframe cannot access DOM of parent page).

[Note: By chance if you are wondering why you should bother about mashups since you have never built them, you are mistaken. If you are embedding scripts for website analytics, social plugins (Like, Tweet, +1 etc.), advertisements, comments system (e.g., Disqus) and so on, you are already having a mashup!]

Though iframes follow same-origin-policy and provide security in some sense, they are well known for their notorious activities like frame phishing, top window redirection, clickjacking, triggering drive by downloads etc. The “sandbox” attribute for iframes which is introduced in HTML5 promises to thwart the problems caused by iframes. Sandbox is currently supported only in Internet Explorer 10, Chrome 17+.

A sandboxed iframe by default disables script, popups, form submissions, top navigation etc. Some of the restrictions can be relaxed by specifying space separated white list tokens (allow-forms, allow-scripts, allow-same-origin, allow-top-navigation).

<iframe sandbox src=""></iframe>
<iframe sandbox="allow-forms allow-scripts allow-same-origin allow-top-navigation"

The details about sandbox and its white list tokens are discussed in several blogs, hence purposefully omitting it here. One interesting feature in sandbox is, when a sandboxed iframe loads content from the same origin as the parent document, the loaded content is still treated as if it originated from cross origin, thereby reducing its script privileges. This restriction can be removed by using the token “allow-same-origin”.

Below are some of the cases where developers have to be cautious while using sandbox.

Disabling Clickjacking Defense:

Even till date, several sites rely on JavaScript based frame busting defense to get rid of clickjacking (X-Frame-Options response header is a better defense, but unfortunately has lesser implementation). Such sites when embedded in a sandboxed iframe are greatly affected. Since sandbox disables JavaScript, the clickjacking protection used in the framed site is lost, hence back to square one!

Allow-scripts and Allow-same-origin combination:

This combination of tokens is a little tricky and could negate the effect  of sandbox. The “allow-scripts” token enables JavaScript inside iframe and the “allow-same-origin” token will give the iframe complete privileges to access DOM of the parent. So if the embedded iframe has a vulnerable input field, script can be injected to remove the “sandbox” attribute altogether and then carry further exploits. Thus the security benefits of sandbox can be removed completely.

Effect on Nested Browsing Contexts:

If a webpage has nested browsing contexts (page containing an iframe which in turn loads another iframe), then reasoning about the effect of sandbox tokens becomes complicated. Let us consider the scenario in the image on the right below-a parent page has an iframe to a page (Child1) with "allow-scripts" sandbox token. Child1 loads another iframe which points to Child2 having "allow-forms" token. At a quick glance, developers may conclude that the innermost page will have both forms and scripts allowed, but it is on the contrary. The inner page has everything disabled and for a good reason! The child1 frame has forms disabled and it will overwrite the "allow-forms" of Child2. Also, Child1 has scripts enabled but Child2 has them disabled. Hence it does not allow script execution. So it is advisable not to manipulate sandbox tokens dynamically, since it is difficult to reason about the after effects on sandbox restrictions.

DEMOS: Click the images for demos (Source at: )

Sandbox demo 1

Sandbox demo 2










In the first demo, there is an iframe with JS based clickjacking protection and by default sandbox option is selected. You can see the clickjacking defense by selecting “normal frame”. So this shows how sandbox defeats JS based clickjacking defense. Also in the same demo you can select “allow-scripts” and “allow-same-origin” optons and inject the snippets provided below the page into the XSS vulnerable page.

In the second demo, inspect the iframes and load them independently in different windows and to see the effect of sandbox tokens in nested browsing contexts.

Hope the article provided some useful information about HTML5 Iframe Sandbox and its secure usage. Feel free to get back with queries or please share aspects which you feel interesting about Sandbox. Happy coding Smile

Presentation on HTML5 Security-OWASP Hyderabad

Happy to say that I had the opportunity to present at OWASP Hyderabad chapter on "HTML5 Security" on 19th May, 2012. The event had awesome audience from diverse backgrounds in security domain-security researchers, penetration testers, security consultants, few developers etc. The talk went for about 2.5 hours(yes!!) and was quite interactive. The audience were very patient, passionate and we had lots of discussions on several interesting topics.


I have built some cool demos for the presentation but the code is not well organized. I shall clean the code and upload to my github account shortly. I would be continuing this talk in next month's OWASP meet too.

JSFoo Chennai 2012–”JavaScript is mischievous. Handle 3rd party content with care!”

It is always exciting to attend a technical conference focusing on a particular theme and even more if you get the opportunity to present. Continuing their good run, HasGeek has organized JsFoo Chennai 2012, India’s first JavaScript conference series, at IIT Madras Research park. There were several interesting proposals made and mine got voted for the final schedule along with other awesome entries.

My session is about the security considerations one should think of while integrating 3rd party JavaScript content into their site (in other words, security of web mashups). 


Presentation: Click here

Demos: Recursive Mashup Attack and Clickjacking

Learning aside, the best part is, I’ve met several awesome passionate geeks, few whom I know on twitter and few I would have never met otherwise. Loved the event even more, since people working on different platforms and having good expertise in JavaScript came under one roof and discussed. Diverse opinions and lots of learning!!

For those who missed, check JsFoo site for videos of sessions, which will be uploaded shortly. Also, here is an interesting review written by one of the attendees.

It is this easy to steal your click!-DevCon 2011

The memories of DevCon 2010, where I presented on “Facebook Apps Development” are still fresh in mind and DevCon 2011 is back! This time I have presented on “Clickjacking”, one of the popular modern web based attacks, using which an attacker can steal user’s click. The session is heavily inspired by the research done by Stanford Security Lab & Internet Explorer Team. It focuses on explaining how users fall prey to clickjacking attacks and what care web developers should take to defend against them.

The event, organized by Microsoft User Group Hyderabad (MUGH), had more than 300 audience and was held at Microsoft Hyderabad campus. 


Presentation: check Slideshare

Demos source code: check GitHub

There were several interesting sessions presented by speakers on cutting edge topics such as Windows Azure, ASP.NET MVC3, Bringing HTML5 experiences to ASP.NET website, Patterns & Practices in C#, SharePoint 2010, SQL Server Denali and Knotting Windows phone 7, Azure & Kinect. The audience were very enthusiastic and interactive, which made the sessions lively. Nice to meet several techies in the event. The learning I had was huge while preparing for this session and answering Q &A :)

The need for HTML5 postMessage API

The postMessage API in HTML5 specification is useful for making cross domain calls across frames. This is typically useful for mashups, Web 2.0 sites (e.g., where different widgets might need to communicate with each other.

HTML5 postMessage Demo

Few developers have already started using HTML5 postMessage in their projects, without knowing why they are using. Here are a couple of questions an inquisitive developer might have in mind:

1. How are mashups and rich Web 2.0 applications built even before HTML5 postMessage API came into existence?

2. What is the trust model which Web 2.0 sites have? (Who trusts whom?)

3. Is there really a need for a new API when workarounds met the needs?

This post tries to answer these questions and explains why postMessage API is important. Though the usage of API looks trivial, the birth of this API is the outcome of several insightful research papers, which are also a motivation for this post.

In the screenshot, the web pages loaded in the top window and iframe are from different domains. On clicking the submit button, the message in textbox is sent to iframe and displayed in the last line. Notice that the top window url (http://localhost/postMessage) has a default port number(80), while the iframe has a different port number (81). Hence the site in iframe is treated as that from a cross domain.

HTML5 postMessage API is as simple as the below JavaScript code.

<script language="javascript">
        window.onload = function () {
            win = document.getElementById("ifrDomain2").contentWindow; //get the target iframe window
            frm = document.getElementById("frmPost");  //get the form which needs to post a message
            frm.onsubmit = function (e) {
                msg = document.getElementById("txtMessage").value;  //get the message to be posted from the textbox
                win.postMessage(msg, "http://localhost:81/");  //post the message to the destination URL
                e.preventDefault();  //prevent default action (suppress postback)

Now let us see why such an API is needed in the first place and try to answer the above questions.

Same Origin Policy and Trust Model:

As most of you know, the Same Origin Policy (SOP) of browsers disallows scripts loaded from one origin to access DOM of another origin (Two sites do not belong to same origin if they differ in at least one of the three- protocol, domain name or port number). Due to this, an AJAX call cannot be made from one domain to another domain from a browser. So far so good, since if this policy is not in place, an attacker can make an AJAX call to your site and grab your cookie.

However, the SOP is not applicable to scripts themselves! Developers can always embed script tags which point to different domains (just as we include reference to jQuery or any JS library from CDNs). If there are scripts from multiple sources, the application is not secure. But this is how mashups and most of our web applications are built! Isn’t this ironical? Moreover, the scripts which are loaded from different domains run under the privilege of the host site. So whether it is external script file or JSONP script injection, the developer should have ‘complete trust’ on the scripts being injected.

As Douglas Crockford rightly points, “A mashup is a self-inflicted XSS attack”. It is more of a work around than a standard.

Instead of loading external scripts in an integrated site, an alternative is to use iframes to load external sites. Since iframes provide complete isolation mechanism, aggregating content is secure, but genuine communication between frames goes for a toss.

Most of the modern Web 2.0 sites rely on external JS libraries, AJAX and JSONP techniques for fetching, manipulating content. In this case, communication between widgets (divs) is not a problem since entire DOM is accessible to any script (bad design w.r.t security as discussed above). Sites using iframe for isolating widgets rely on “fragment identifiers” (e.g., for communicating between widgets (has confidentiality but no authentication and integrity). These (flawed?) solutions answer our 1st question.

So the trust model we have is, you as a developer/site owner should either trust all (in case of scripts) or trust none (in case of iframes), but nothing in between. This answers our 2nd question. You may trust the JavaScript provided by Google analytics, maps, facebook widgets etc., but this dependency on ‘trust’ does not scale well.

Browser vs. OS:

The modern web has seen data intensive, rich and interactive web applications, which mimic desktop applications. Mashups, which are applications that combine data from multiple data sources, have changed the boundaries of a web browser. Concepts like Web OS started evolving which guided researchers to draw a parallel between browsers and OS.

  • The “system calls” in OS are analogous to “DOM calls” in browsers
  • “Processes” in OS are analogous to “Frames” in browsers
  • “Disk storage” in OS is analogoius to “cookies, localStorage, IndexedDB etc.” in browsers
  • In an OS, “Users” are the principals (which need to be distinguished), whereas in a browser, “Origins” are the principals.

Browsers, which were designed to handle pages from a single domain at a time are now forced to handle pages/data from multiple domains. In other words, as researchers say, web browsers have evolved from a single-principal platform to multi-principal platform. However, unlike OS which can easily handle multi-user scenarios, web browsers prior to HTML5 postMessage did not have the capability to abstract multi-principal scenarios. Their trust model remained the same as discussed above.

Hence, there is a need for a newer standard supported by browsers, which can securely abstract multiple principals and provide communication between them, thereby improving the trust model (answers 3rd question). There were several recommendations like JSONRequest, Verifiable Origin Policy, CommRequest etc.,as described in the references, for solving these problems and finally, the HTML5 postMessage API came into existence.

//Syntax of HTML5 postMessage
otherwindow.postMessage(message, targetOrigin); //Clearly, the "targetOrigin" parameter improves trust!

The postMessage channel, which is designed for cross site communication, guarantees confidentiality, integrity and authentication and improves trust (A frame can now communicate with a trusted frame by specifying the target). With this standard in place, frames can now be attractive feature to integrate 3rd party content, create widgets with improved trust. It is supported by majority of modern browsers (IE8+, FF3+, Chrome, Safari, Opera 10+).

Hope the article helped in understanding why HTML5 postMessage is needed and possibly pointed out the mistake you are doing by not using it for your requirements. Let us build a more secure and standard compliant web, one website at a time Smile


1. “Securing Frame Communication in Browsers” – by Stanford web security lab

2. “Protection and Communication Abstractions for Web Browsers in MashupOS” – by Microsoft Research & Stanford web sec lab.

Create your own web based slide shows in ECMAScript 5

Web based slide shows (built using HTML, JS, CSS) have always been my choice and I use them most of the times in my presentations. This post explains how you can create your own web based slide show from scratch, using ECMAScript 5 (ES5). In fact, this is the code walkthrough of my presentation on ECMAScript 5 at TechEd on the Road.

Note that while you can always build the same by the non-ES5 way, I am using ES5 just to highlight the new object model and other features which are very much useful.

Final product: Check my presentation on ECMAScript 5.

Source Code: Check my GitHub repo and use it as you like.

There are a lot of existing solutions which can be used straight away, but I made the above presentation to meet the following requirements:

  (1)  Demonstrate the power of ECMAScript 5 with a live demo, using the presentation itself

  (2)  Load my slides asynchronously (the existing solutions have all slides in a single file which makes the presentation heavy).

  (3)  Run code snippets within the presentation itself, so that I need not switch windows for demos.

You can have a quick look at the directory structure at my GitHub repo.

The index.html file is the one which loads initially. Each slide is a 'html' page containing basic <ul>, <li> tags and all slides are located in the 'slides' folder. The idea is to load these files via AJAX using jQuery. The 'CSS' folder contains the images and styles needed for styling the presentation.

The most important components are the JavaScript files located in the 'js' folder. I have used jQuery and a plugin for the slideshow effect. You may use the jQuery presentation plugin for the sliding effect or use mine (a tweaked version to suit my requirements). Just download the entire directory and modify the html files in 'slides' directory and the 'images' for an instant presentation.

Digging into the code:

The entire logic of the presentation is in the common.js file (here it is on github). I suggest you to switch between the source code and this article for better understanding. I have used my favorite "Revealing module pattern" to keep the code clean and maintainable(refer my JS design patterns article for more info). This pattern is good for encapsulating private variables and reveal only the required one's in the 'return' object.

Here is the basic structure of my self-executing anonymous function: 

var $es5 = (function ()
    var myPrivateVariable;
var foo=function () { /* blah blah.. */ };
var bar=function () { /* blah blah.. */ };
return {  init: foo }

So $es5().init(); will execute foo(). You can return 'this' in each function and chain in jQuery style. Skipping the internals, as it is out of scope now. 

Checking for ECMAScript 5 browser support: 

Before implementing ES5 code, we have to check if browser supports ES5 standards or not. A simple test is to see if the new ES5 object properties are available:

    if (!Object.defineProperties || !Object.defineProperty) { /*Browser does not support ES5. Return */ }

Freezing your JS code:

One nice feature of ES5 is that you can freeze your objects after creating them. This means, your code cannot be tampered by script injection once it is freezed.

  $es5.init(); //invoke the  $es5 function & create an instance.

  Object.freeze($es5); //freezing the object using ES5.

Iterating using ES5 'forEach' method:

JavaScript cannot access file system as a security measure and we cannot read the markup from our html slides. So the trick to do our task is store our html file names in a string array, iterate through the array and load the files via AJAX. For iteration, we can use the ES5 'forEach' method, which will help us in avoiding pointer variables like 'i', 'j' in for loops.


Using ES 5 getters and setters:

Another beauty in ES5 is you now have getters and setters similar to languages like C# and Java. Let us create a 'slideTemplate' object, which can be inherited by other objects in future. The idea is to have a setter method called 'path', which will accept a URL and generate some markup. The getter method 'content' will return the markup generated by the setter.

   var slideTemplate = {        
        content: {                  
            get: function () {    /* return markup; */   }       
       path: {            
           set: function (url) {  /* load slides via AJAX */    }        

Loading slides via AJAX:

Now, we need to use the setter method for loading our slides into our main page. Instead of appending each slide to the DOM (bad for performance), we can create a document fragment in JavaScript like:

    var slideFrag = document.createDocumentFragment();

We need to load markup using jQuery's $.ajax into 'slideFrag' and finally add it to a container in index.html.

Creating a new slide using ES5:

Here comes the most beautiful part of ES5. You can create plain vanilla objects or inherit from existing objects using "Object.create" method. The 'slideTemplate' object which we created above can be inherited to create new objects. To put it in real sense, the new object we are creating is in fact a new slide! Isn't this real object oriented programming?

    var newSlide = Object.create( {}, slideTemplate);   
    newSlide.path = url;        //setter gets invoked!
    container.append(newSlide.content); //getter gets invoked!

To summarize, we are basically iterating over our array of html file names. For each file name, we are creating a new object and assigning a URL. On assignment of the URL, the setter gets invoked and loads markup from remote content via AJAX into a document fragment. Then we are appending the document fragment to the container using the getter.

Inline demos: That's easy to figure out from the code. So leaving it to you, the reader :)

Hope the article helped in understanding how to use some of the new feautres ECMAScript 5. Play around with the code and let me know if you can improve it better.

Happy coding :)

TechEd on the road-new features in ECMAScript 5

Happy to say that today I have presented at "TechEd on the road", a developer conference at Microsoft Hyderabad, on "JavaScript APIs and enhancements in ECMAScript 5". It is one of the premier tech events, organized by Microsoft User Group Hyderabad (MUGH) with audience in both developer and IT Pro tracks.


As in most of my sessions, I tried to use web based presentation instead of traditional power point. I developed my presentation using HTML5, jQuery and leveraged the new features of ECMAScript5, just to showcase a real time demo.  The response of the audience and fellow speakers was very cool and probably the presentation was worth the effort :)


Presentation & Demo: Click here


Note that you need ECMAScript5 supported browser to run the slide show. You will get a prompt if your browser doesn’t support ES5. Run it in full screen and use 'right', 'left' keyboard keys to navigate.


For the presentation, I have checked several existing solutions like S5, HTML5rocks slides etc., but I wanted inline code snippets as demos . So wrote my own slide show system and it came out well. Probably, I shall write another article on how I have developed it.


Have thoughts of generalizing this web based slide show and releasing it on github/codeplex. Play with the presentation and get back with your thoughts :)

Update: You can check about the proceedings and pictures of the event in my friend Phani's blog.

ECMAScript 5 'Strict mode' support in browsers. What does this mean?

If you are closely following how the web is shaping up lately, you would be thrilled, like me, looking at pace at which things are changing. There are hundreds of things happening on the new HTML5, CSS3, JavaScript front, frequently releasing browser versions and contest for speed, supporting modern standards etc. One such innovations is ECMAScript 5 Strict Mode support in modern browsers. Recently, IE10 platform preview 1 announced 'strict mode' support in Mix 2011 conference . The goal of this article is to explain what 'Strict Mode' support in modern browsers mean and how developers can take advantage of it.


I am aware of JavaScript. But what is ECMAScript 5?

Similar to W3C which standardizes HTML specifications, ECMA is the body which standardizes JavaScript. ECMA-262 is the specification which defines the JavaScript language, interchangeably referred as Jscript/ECMAScript. The JavaScript code which we web developers have been using since a decade is as per the guidelines defined in the Third edition ofECMAScript (ES3 in short) released in December,1999.


ES3 was released in a hurry and it had several loopholes, which means that the future versions have to be built on top of these loopholes to support older pages (I strongly recommend reading grandpa Crockford's book, JavaScript- The Good Parts to know the good and bad parts of the language). ECMAScript 4 had several ambitious, drastic changes in its specs but was never released due to conflicts regarding backward compatibility, fearing a broken web. So,ECMAScript 5 (ES5 in short) was released in December 2009, more as a transitional version of the specification, adding few cool features, without much changes in the syntax (Check the ECMAScript specs archive).


Few new features in ES5:

ECMAScript 5 includes few new APIs, computational methods for things which can already be done in ES3. One of the most interesting features is the newer object model in ES5, using which, newer objects can be created easily and their extensibility can be controlled. Similar to higher programming languages like Java or C#, JavaScript objects now have getters and setters, non-enumerable methods, sealed and frozen objects  etc. ES5 also describes native JSON support, which includes methods like JSON.parse() and JSON.stringify() which remove dependency on external libraries for working with JSON.


Each browser has its specific implementation of ES5, as per its JS engine. ES5 support in IE 9 is different from ES5 support in FF 4.


ES5 Strict mode:

'Strict mode' is an innovative feature of ES5. It is a restrictive variant of ES5 implementation, which follows a slightly different semantics from the normal JavaScript. Someof the deprecated, bad parts of JavaScript in ES3 specification are disabled or thrown as exceptions in 'strict mode'. It is not backward compatible with older browsers and has to be opted-in by the developer.

To enable ES5 in strict mode, just use the string "use strict" as the first line of your JavaScript code. This will make the entire program to run in strict mode.


Alternately, you can place "use strict" in a function, to restrict only to that context.


function isStrictMode(){

return !this;


//returns false, since 'this' refers to global object and '!this' becomes false


function isStrictMode(){   

"use strict";

return !this;


//returns true, since in strict mode, the keyword 'this' does not refer to global object, unlike traditional JS. So here,'this' is null and '!this' becomes true.


I hope to cover detailed demos on this in the following posts.


The good parts of  ES5 Strict Mode:

In JavaScript, if a variable is not explicitly declared, it is implicitly assigned global scope.This may look fun to code in JS, but is a nightmare to maintain in huge projects. Strict mode throws error if variables are assigned values without declaring and hence implicit global variables will not be created. This is a huge win for the language as well as for huge projects.


Few such good changes in strict mode are: Assignment to a read-only property will throw error, object literals having 2 or more properties with same name will throw error, functions having 2 arguments with same name will throw error etc. All these changes will help in making the code more reliable, readable and manageable.


The IE team launched  a 'Strict Mode' demo in their IE Test Drive HTLM5 demos. You can check if your browser supports ES5 Strict mode or not by checking the "Try Strict Mode" demo. Download IE10 platform preview 1 if you haven't and start playing with it!


P.S: Happy to share that Microsoft has recognized my community contributions and awarded me "Microsoft MVP award" for the second consecutive year. In 2010, it was under ASP.NET/jQuery category and now for 2011, it is under "InternetExplorer" category. Thanks to Microsoft for the encouragement Smile