Saturday, December 10, 2011

Browser cookies can also be created this way...

While inspecting some public websites I came across an interesting server-side-cum-JavaScript way of creating cookies. Well this must be an old technique, but nevertheless I am quite new to it.

The server-side code is the easy part. Because I assume people would have done this at sometime in their software development lifetime. If not just take a look at the following codeproject article: Beginners guide to ASP.NET Cookies

The JavaScript side of how things are to be done, I saw a code something like this:

var img = new Image();
img.src = '';

That's it. This particular code of javascript when executed will create the cookie, provided the url in the above example returns a response that set the browser cookie. The particular image object isn't even added to the DOM, but the cookie is created and associated with the page!

The main advantage is, you don't have to have the hassle of creating cookies via javascript; especially cookies which belong to other domains (different from your website). In those websites we were supporting the main rationale was reuse, and maintainability. So they added similar code in a separate js file and added it to the page manually. When they didn't want it they'd manually remove it and edit the page. They didn't have the need to make any change to server side code to add/remove those cookies.