My JavaScript book is out! Don't miss the opportunity to upgrade your beginner or average dev skills.

Saturday, December 20, 2008

Visual Studio 2008 and JavaScript: the worst couple ever

We are using Visual Studio 2008 Team Edition at work and it is great for our C# plus SQLServer application, but I am working entirely with JavaScript and every time my files grow up "too much" I start having headache scrolling up and down thousands of line of code.

A basic function that even a small editor like Notepad++ has, the plus/minus sign to close functions closures, does not exists.

You should try to create your own macro, in VB "of course", and call it every time.
As alternative, I added the file extension js in the option with HTML Editor as default editor to let me do something like this

//#region MyConstructor <script>

... my code

//#endregion </stript>

Above start and end comment allows me to close code blocks and everything inside will be highlighted because the editor consider it as an HTML JavaScript tag:
it's true, HTML has open/close blocks while JavaScript does not.

The "fantastic" debugger is nothing that better than the one you can find inside Internet Explorer 8, the only point is that it is integrated with the rest of the project so you can debug both JavaScript and C# at the same time ... without this big effort.

I use FireBug and/or Chrome console indeed, since I do not need to monitor C# that much, and that's it, client side debug feature completely useless under IE ( and I downloaded the version 8 beta 2 yesterday so I can use its debugger instead of launching another local server for client side debug ... )

The intellisense sucks, it does not work automatically as is for C# or other languages or as is for Eclipse or Aptana, you have to put useless syntax in the top of the file to tell the big IDE where are other files.

The suggestion is so clever that if you have a property whose name starts with el, the IDE will autmatically put an else

myObject.else // by the ide


The internal parser does not recognize properly functions as objects, and inheritance is not part of the suggestion ... you should try to disable it if you want to code faster instead of correct IDE suggestions.

In few words, I still wonder why Microsoft is doing everything to discourage the usage of JavaScript and I can't wait to find a valid alternative to integrate my JavaScript projects into source control without being constricted to use the best IDE for C# and the worst ever for JavaScript: Visual Studio 2008

Kind Regards

Wednesday, December 17, 2008

outerHTML for almost every browser ... if you need it ...

We all have to deal with memory leaks problem and apparently a good way to be sure that an HTMLElement has been removed from its "flow" is the outerHTML assignemnt (thanks Ariel for the suggestion)

element.outerHTML = "";
element = null;

If the element is not a document.body or another body parent node, Internet Explorer will "extract" that element from its context, if any, and if there are no other references for that element the null assignment will, theoretically, complete the opera, hopefully solving memory leaks problem for that node as well ...


To remove ... but to replace too ...


Every library has a "swap" or replace method to quickly change an element, but even if we all know that innerHTML is the fastest way to insert content, few libraries use outerHTML to replace nodes, that as far as I know, should be "that fast" in IE as innerHTML is:

// traditional swap, the DOM way
function swap(oldNode, newNode){
var parentNode = oldNode.parentNode;
parentNode.insertBefore(newNode, oldNode);
parentNode.removeChild(oldNode);
};

// spaghetti swap, the outerHTML way
function swap(oldNode, newNode){
oldNode.outerHTML = newNode.outerHTML;
};



outerHTML ... both get and set



try{
HTMLElement.prototype.__defineGetter__.length;
(function(body, removeChild){
HTMLElement.prototype.__defineGetter__(
"outerHTML",
function(){
var self = body.appendChild(this.cloneNode(true)),
outerHTML = body.innerHTML;
body.removeChild(self);
return outerHTML;
}
);
HTMLElement.prototype.__defineSetter__(
"outerHTML",
function(String){
if(!String)
removeChild(this);
else if(this.parentNode){
body.innerHTML = String;
while(body.firstChild)
this.parentNode.insertBefore(body.firstChild, this);
removeChild(this);
body.innerHTML = "";
};
}
);
})(
document.createElement("body"),
function(HTMLElement){if(HTMLElement.parentNode)HTMLElement.parentNode.removeChild(HTMLElement);}
);
}catch(e){};



Conclusion


pro and cons are the same of innerHTML and the reference is lost as is for Internet Explorer, whenever we decide to use this dirty approach to remove or change elements in the DOM. A last example?

function change(strong){
strong.outerHTML = "not strong anymore";
strong = null;
};
onload = function(){
document.body.innerHTML = "click";
};

Saturday, December 06, 2008

A fast and crossbrowser function to make an Array

An absolutely common task present in almost every library, is to transform a generic collection/list of objects or DOM Elements into a friendly Array.

Cases Scenario



  • It is possible to apply directly an Array.prototype.slice call to quickly return an Array

  • It is not possible at all apply every kind of Array prototype to the list



Cases scenario detection


When we execute a piece of JavaScript in a web page, we can assume that we have at least one DOM element in that page, as the script itself for example, so it is always possible to obtain a collection of elements calling document.getElementsByTagName("script") or a generic ("*") in this case probably superflous considering the latter assumption.

Cross browser and fast makeArray proposal



var makeArray = function(push, slice){
try{
// Andrea Giammarchi proposal
slice.call(document.getElementsByTagName("script"), 0);
return function(array, results){
array = array instanceof Array ? array : slice.call(array, 0);
results ? push.apply(results, array) : results = array;
return results
}
}catch(e){
return function(array, results){
if(!(array instanceof Array))
for(var ret = [], i = 0, length = array.length; i < length; i++)
ret[i] = array[i];
else
var ret = array;
results ? push.apply(results, ret) : results = ret;
return results
}
}
}(Array.prototype.push, Array.prototype.slice);


Summary


The try catch is executed only once, the Array prototypes are cached once as well to guarantee cross libraries compatibility. The function is assigned differently for those browsers that can apply the slice prototype to the collection and those that cannot (mainly Internet Explorer).
Accepted parameters are two, inspired by Sizzle function, to allow us to concatenate elements into a collection.

The collection is transformed into an Array only if necessary, since it does not make sense to perform a slice call in every case.

Compatiblity? It should be every browser that supports try and catch statement :-)

Wednesday, December 03, 2008

Stressfull procedure? Distribute your task!

Have you never been in troubles with frozen GIFs or unresponsive HTML?
Sometimes JavaScript could be used to perform really stressful task and a loop, a for in, or an each, could not be fast enough to make your DOM responsive.

What we need in this case is simply a closure to make sure references are consistent and our job will end up in the correct order.

This is a probably silly but I hope interesting function to make the DOM and generally the page more responsive:

Time = {
setTimeout:function(Stack, delay){
var self = this;
if(!delay)
delay = 1;
if(!(Stack instanceof Array))
Stack = [Stack];
setTimeout(function(){
Stack.shift().call(self);
if(0 < Stack.length)
setTimeout(arguments.callee, delay);
}, delay);
}
};

We can call this functon in different ways, stating from the demo:

Time.setTimeout([
function(){
alert("Hello");
},
function(){
alert("Distributed");
},
function(){
alert("Work");
}
]);

untill its more meaningful usage:

var distributed = [];
$("whatever").each(function(i, dom){
distributed.push(function(){
// your stuff to do with i or dom element
});
});
distributed.push(function(){
// your stuff to do after the each call
});
Time.setTimeout(distributed);

Another trick? The usage of the scope injected by each function:

$("whatever").each(function(i, dom){
var self = this;
distributed.push(function(){
return function(){
// your stuff to do with i or dom element
}.call(self);
});
});

Closures against Responsiveness


People expect usability, we expect performances ... at the same time we would like to be able to show a progress, something, that indicate that the page is not completely blocked.

This is a simple way to solve the problem, portable enough, and customizable via closures ... I hope you'll enjoy it :)

Tuesday, November 18, 2008

Ext JS - How to hack the JsonReader

I have a new job ( hooooray?! ) and I suggested Ext JS framework as web UI to focus more about Ajax, XML + XSLT data interactions rather than problems with CSS, events delegations, etc ... and I guess I am doing well, so well, that here I am with a simple tiny trick to hack an Ext.data.JsonReader instance, specially the root and the totalProperty params:

// directly from Ext JS 2.2 API site
// http://extjs.com/deploy/dev/docs/

new Ext.data.JsonReader({
totalProperty: "results", // The property which contains the total dataset size (optional)
root: "rows", // The property which contains an Array of row objects
id: "id" // The property within each row object that provides an ID for the record (optional)
})

Especially for the paginator toolbar, the JsonReader is a must to surf a big amount of data without stressing too much both server and client sides.

One nice feature, or one clever way to make the root node customizable, is the usage of evaluated code via a new Function call.

If the root property ontains a dot, that property is retrieved via nested objec properties.


...
root:"items[0].myList",
...

Thanks to this feature, it is possible to pre parse and pre generate the list that will be assigned as root Array, the one used inside the Grid, DataView, or whatever.Component is managing your interactions.

The trick to pass the returned object to an arbitrary function is this:

...
root:"toString.length||callback(obj)",
...

The callback suppose to be a valid function with a global scope that will return a filtered list of objects compatible with the column model or the data manager we chose.

The trick is based on their regexp that checks simply a dot or a square bracket "[" in the passed string.

That's it, let me discover better tricky stuff in the source and I'll post them :D

Thursday, October 30, 2008

3, 2, ... 1, ... Coming Soon!

Guys, I can't wait for Ubuntu 8.10 and what's up in the website?
The countdown now shows a "Coming Soon" message ... I mean, a little news about when is that difficult?


I know there is a kernel problem since 27 October, and i hope you updated are updating the release to fix that problem with the 8.10 ... but shall you tell us more?
Kind Regards

And thank You :)

Tuesday, October 28, 2008

jQuery plug-in distributed elements via If, ElseIf, and Else

After a couple of instant and consecutive releases, I ended up with a plug-in that fits minified into 240 bytes :)

Here is the official plug-in page, while this is the example page and this is the summary:

;jQuery.fn.extend({
// Andrea Giammarchi - Mit Style Licence - V0.2
If:function(fn){
var __If__ = this.__If__ || this,
$ = __If__.filter(fn);
$.__If__ = __If__.filter(function(){return !~$.index(this)});
return $;
},
Else:function(){
return this.__If__;
},
Do:jQuery.fn.each
}); jQuery.fn.ElseIf = jQuery.fn.If;

Monday, October 27, 2008

jQuery If, ElseIf, and Else plugin

Update
Guys, I have to admit I created silly prototypes while all I need were much more simpler than I though :) Enjoy last version!
-------------------------------------

Try to imagine a page like this one:

<body>
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
<div>7</div>
<div>8</div>
</body>


.. and now try to imagine something like this:

function oddNumbers(){
// return true if element contain an odd number
return $(this).text() & 1;
};

$(function(){
$("div")
.If(function(){return $(this).text() == "3" || $(this).text() == "5"})
.text("match the 3 or 5 check")
.ElseIf(oddNumbers)
.text("odd numbers")
.ElseIf(function(){return $(this).text() == 2})
.Do(function(){ // if you need a closure ...
$(this).text("text is equal 2");
})
.ElseIf(function(){return $(this).text() == 6})
.text("match the 6 condition")
.Else()
.text("this is 4 or 8");
;
})


... now, try to imagine I created a plugin like this:


;jQuery.fn.extend({
// Andrea Giammarchi - Mit Style Licence - V0.1f
If:function(fn){
var $ = this.filter(fn);
$.__If__ = this.filter(function(){return !~$.index(this)});
return $;
},
ElseIf:function(fn){
var $ = this.__If__.filter(fn);
$.__If__ = this.__If__.filter(function(){return !~$.index(this)});
return $;
},
Else:function(){
return this.__If__;
},
Do:jQuery.fn.each
});


... and now try to enjoy it :D

Kind Regards

Thursday, October 23, 2008

Subclassing JavaScript Native String

Just a quick post about subclassing native String constructor.
All we need is to redefine valueOf and toString methods.

function $String(__value__){
this.length = (this.__value__ = __value__ || "").length;
};
with($String.prototype = new String)
toString = valueOf = function(){return this.__value__};

With incoming V8, TraceMonkey, Squirrelfish, and other (if any ...) advanced engines that transforms repeated code into machine one, performances wont be a problem anymore and everybdy could create its own implementation of the String.

Of course, these statements will be preserved:

var s = new $String("abc");
s instanceof String; // true
s.constructor === String; // true

while typeof will return an object but we can easily use another method such:

$String.prototype.type = function(){
return "string";
};

alert(typeof s); // object
alert(s && s.type()); // string

concat as other native methods willl work, but returned object, unfortunatly, wont be a $String.

Wednesday, October 22, 2008

Big Douglas begetObject revisited recycling a unique function

With the precedent post I realized I wrote a really tricky way to extend inline a function.Next code is the snippet summary:

MyExtendedConstructor.prototype = function(Function){
var callee = arguments.callee;
if(!(this instanceof callee)){
callee.prototype = Function.prototype;
return new callee;
}
}(MyBaseConstructor);

Above code uses the closure itself to create the intermediate constructor.
The reason i chose this way to operate that task was: why should I use another function when I already have one that is the closure itself?

Well done, one function instead of two ... but wait a second, why should I create a different function everytime instead of recycle a single one?

Douglas Crockford begetObject concept


In one of His historical posts, Big Douglas describes simple JavaScript inheritance and object cloning using an intermediate constructor. This is the Object.create function:

Object.create = function (o) {
function F() {}
F.prototype = o;
return new F();
};

Above snippets is still used in I do not know how many JavaScript libraries or code over the net, to extends constructor prototypes or to create a clone of a generic object.

The snippet is clever, powerful, "perfect" for its purpose, but it creates many functions for each object and your JS engine, as your RAM, has not shields to prevent its aggressiveness when you use thousands of times that snippet.

This is a benchmark function example:

function bench(create){
for(var original = {test:"test"}, o = create(original), i = 0, time = new Date; i < 500000; i++)
o = create(o);
return new Date - time;
};

If we test above function with Douglas Object.create one, the result will be something like:

FireFox 3.0.3 - Intel Core2 6600 @ 2.40 - 2GB DDR2 RAM
------------------------------------------------------
Memory: 121.676 Kb
CPU: 50% (not responding)
Elapsed time: 1769 ms



Object.create revisited version


Next snippet is my revisited version of that function:

Object.create = function(Function){
// WebReflection Revision
return function(Object){
Function.prototype = Object;
return new Function;
}}(function(){});

these are advantages about recycling the function:

  • memory should not be increased, the function is one

  • execution speed should be faster, no functions created for each call

  • apparently, not a single behaviour different from the good old snippet


While these are results with the same configuration:

FireFox 3.0.3 - Intel Core2 6600 @ 2.40 - 2GB DDR2 RAM
------------------------------------------------------
Memory: 37.332 Kb
CPU: 35% (responding)
Elapsed time: 855 ms

Seems to be quite impressive, isn't it? Results are tremendously different with Internet Explorer, where the good old way lets the browser ask if it is the case to stop the script: thousands of milliseconds against approximately 1200 with my revision.

Not only to clone


I tested my revision to extend constructors as well, and everything seems to be absolutely fine. This is the function, based on the precedent one:

Function.extend = function(A, B){
A.prototype = Object.create(B.prototype);
A.prototype.constructor = A;
};

// Usage Example
Function.extend(MyExtendedConstructor, MyConstructor);


Why does it work?


Everything is about the clone strategy itself. When we clone an object, it does not matter that the original one is modified, the cloned will be an object a part.
Since the constructor used to create the clone is private, and since it is never modified by the function itself, it does not matter how many times we reassign its prototype, since the only important thing is when we create an instance with new keyword. That instance wont loose its inherited methods or properties.
As example:

function A(){};
A.prototype = {sayHello:function(){alert("Hello")}};
var a = new A;

// prototype redefinition
A.prototype = {};

alert(a instanceof A); // FALSE
a.sayHello(); // Hello

As I said, when variable a is created, it inherits everything from A.prototype and, of course, if A.prototype inherits from another constructor, the chain is respected and classic inheritance emulated. Using the unique function inside that closure, we are doing something like this:

function A(){}; // generic constructor

function Intermediate(){}; // intermediate function
Intermediate.prototype = {sayHello:function(){alert("Hello")}};

// assign the prototype creating an instance
// the instance does not loose its methods
// inherited during its constructor
A.prototype = new Intermediate;

var a = new A;

// we are changing the constructor prototype
// but A.prototype is an instance of the precedent one
Intermediate.prototype = {};

// the method is still there
a.sayHello();

// the prototype has not been changed
// when created it inherited precedent
// methods or variables
var b = new A;
b.sayHello();



Conclusion


In my opinion there aren't side effect but only performances and memory consumption improvements for every browser.
I do not know why I did not think about this way to recycle that function before, but for sure I will never use a new intermediate constructor again, unless somebody will post valid reasons to do it.
Finally, if everybody knew about this tricky way to recycle the constructor, I am sorry, I am late.

a new Relator object plus unshared private variables

This is a Robert Nyman's post dedicated reply, about JavaScript inheritance and alternatives and private variables.

First of all, I would like to say thanks to Robert for both interesting articles He is writing about JS inheritance, and a link to a personal comment which aim was to bring there my "old" documentation about classical JavaScript inheritance and usage of prototype, closures, and public, privileged, or private, scope when we create a constructor.

About


Last Rob's post talk about private variables, describing them as shared, if present outside the constructor, and valid only for singleton instances.
This is true, and could cause a lot of headache if we are not truly understanding closures and prototype shared methods behaviour, but there is a way to use this peculiarity about shared private variables to create dedicated private variables.

Before I will write about it, let's look into a generic shared private variable example:

Click = function(){
// closure for private methods / variables

// private shared variable
var _total = 0;

// returned constructor + prototype
function Click(){};
Click.prototype.add = function(){
_total++;
};
Click.prototype.getTotal = function(){
return _total;
};
return Click
}();

var left = new Click,
right = new Click;

left.add();
alert(right.getTotal()); // 1

Above example shows that if a variable is created outside the constructor and prototype shared methods use that variable, every call to one of those method from a generic instance will modify that single private variable, created once inside that closure. To obtain a private variable we need privileged methods:

Click = function(){ // privileged methods
var _total = 0;
this.add = function(){
_total++;
};
this.getTotal = function(){
return _total;
};
};

var left = new Click,
right = new Click;

left.add();
alert(right.getTotal()); // 0

As discussed before in my doc, in robert's posts, and everywhere else in the web, privileged methods create many functions for each instance, and with big projects this is not good for both memory and CPU usage.

new Relator object and unshared private variables


The Relator is an object capable to relate a generic variable with a clear object, without modifying the original variable.
The classic example is this:

var myNum = 123;
Relator.set(myNum).description = "I am number 123";
alert(myNum.description); // undefined
alert(Relator.get(myNum).description); // "I am number 123"

Since with Relator it is possible to create a unique relation between a generic object and a private Object, it was natural for me to think that a private variable could be a Relator like object using this as unique relationship.
The new version of my Relator still respect the precedent API, being a Relator itself, but is now able to return a new object Relator like that could be used, as example, inside a closure.

// new Relator can create a Relator like object with method "$"
PrivateRelator = function(Relator){
// Relator argument is a new Relator like object
// present only in this scope
return {
get:function(what){
var value = Relator.get(what);
return value && value.value;
},
set:function(what, value){
Relator.set(what).value = value;
}
}
}(Relator.$()); // create a new Relator

Relator.set(window).value = "Hello World";
Relator.get(window).value; // Hello world
PrivateRelator.get(window); // undefined
PrivateRelator.set(window, "Hello Private World");
PrivateRelator.get(window); // Hello Private World
Relator.get(window).value; // Hello World

The good part of Relator is that the stored variable, if it is an object, is stored by reference, and we can assign more than a private unique relationship between a single object and our extra informations.
The same pattern could be easily re-adapted to create a shared private variables:

Person = function(){

// private methods
function _getName(){
return _private.get(this).name
};
function _setName(name){
_private.get(this).name = name;
};

// private variable, shared by every function in this scope
var _private = Relator.$();

// constructor + prototype
function Person(){
// bridge to _private shared variable
_private.set(this);
};
Person.prototype.getName = function(){
return _getName.call(this);
};
Person.prototype.setName = function(name){
_setName.call(this, name);
};
return Person;

}();

// extended constructor
function Enhanced(){
// necessary to save
// this instance into _private variable
// accessible only via Person scope
Person.call(this);
};
(function(){ // quick runtime extend
var callee = arguments.callee;
if(this instanceof callee)return;
callee.prototype = Person.prototype;
Enhanced.prototype = new callee;
})();


var me = new Person(),
rob = new Enhanced();

me.setName("Andrea");
rob.setName("Robert");

alert([me.getName(), rob.getName()]);
// Andrea,Robert


Conclusion


Sometime a limitation could be easily managed to obtain desired result.
In this case, thanks to JavaScript closures and its prototype nature, the shared variable become a sort of bridge to obtain private variables for each instance.
It is important to understand that even if we extend the base constructor, every new instance will still persist into original _private variable, inside the Person scope, unless we do not specify a different one, redefining every method that use that variable as well:

(function(_private){
Enhanced = function(){
_private.set(this);
};
(function(){ // quick runtime extend
var callee = arguments.callee;
if(this instanceof callee)return;
callee.prototype = Person.prototype;
Enhanced.prototype = new callee;
})();
Enhanced.prototype.getName = function(){
return _private.get(this).name
};
Enhanced.prototype.setName = function(name){
_private.get(this).name = name;
};
})(Relator.$());


See you soon ;)

Wednesday, October 08, 2008

JavaScript bits and bops :-)

This post is about a couple of probably useful JavaScript functions, that on daily basis could make our code smarter ;)

String.prototype.Replace


Ok, ok, a prototype into a native constructor is not a good start point, but this one, strings dedicated, is probably one of those "must have" protos, a Replace with multiple inputs, as is for PHP.

String.prototype.Replace = function(replace){return function(RegExp, String){
if(!(RegExp instanceof Array))
RegExp = [RegExp];
if(!(String instanceof Array))
String = [String];
for(var result = this, i = 0, l = 0, index = RegExp.length, length = String.length; i < index; i++)
result = replace.call(result, RegExp[i], String[l < length ? l++ : l - 1]);
return result;
}}(String.prototype.replace);

With above prototype it is possible to search and replace with multiple RegExps and multiple replacements. The proto works as native replace one, but it is possible to perform a replace like this as well:

"abc".Replace([/a/, /b/, /c/], "d"); // ddd
"abc".Replace([/a/, /b/, /c/], ["c", "a", "b"]); // cab
"abc".Replace([/a/, /b/, /c/], ["d", function(){return "e"}]); // dee

Tricky enough?


A meanwhile function pattern


Sometime we need two arguments for a generic callback, but sometime we need to do something between the first argument and the second one.
A common generic example could be a time based callback, where we need to get a start time, to perform an operation, and then an end time.
With a simple pattern like this one:


function meanWhile(before, after){
if(2 < arguments.length)
after = arguments[arguments.length - 1];
// do stuff ... return other stuff
return after - before;
};

We are able to execute a couple of interesting operations.
A timing example is this one:

function bigLoop(){
for(var i = 0, max = arguments[0] || 1000000; i < max; i++);
};
meanWhile(new Date, bigLoop(), new Date); // 180 or less if your PC is faster
meanWhile(new Date, bigLoop(), bigLoop(), new Date); // 360 or less ...

Can you imagine better applications?

P.S. It's long time I do not post guys, sorry but it's really a busy period :)

Wednesday, September 17, 2008

jSmile 0.4 - Stand alone Version

nic comment:
hey. thank u for that awesome plugin. how can i download the smilie package? i want to host them on my webspace because i want to be independet from other hosters.

I have recently updated my jQuery plugin, called jSmile, and the biggest news is that it does not require anymore external resources.

Thanks to inline uri data, the script now comes "full optionals", or better, with base64 encoded GIFs images included.

Instead of external CSS classes, images, and cross host dependencies, jSmile can now easily be integrated in every http or https site, and without network delays.

Its size is obviously bigger than before, but using a minifier and gzip compression, it fits perfectly under 7Kb.

Compatibility



  • Chrome

  • FireFox

  • Internet Explorer 8

  • Opera

  • Safari

  • WebKit



Enjoy ;)

Tuesday, September 09, 2008

Internet Explorer Security Hole - A Better Example

Again, about the security hole I talked about last posts, but this time with a really simple example.

How does the example work



  • Open Internet Explorer, whatever version

  • Go in this page

  • Write a fake user name and a fake password, or a fake email address and a password

  • Click Submit



What does the example do



  • Emulates user actions via javascripts

  • with some version of IE, it could be able to grab both fields values

  • in any case, it demonstrates you that every site could steal your compiled fields in every other site, if the autocomplete option is not forced to be disabled



What could do a malicious, and hidden, code



  • steal your data

  • steal your email

  • steal your credit card information (a really famous company, as example, suffers this problem, so somebody could steal credit cards details of million of people)

  • steal your details

  • steal your searches via common search engines

  • etc, etc



More details in my old post I wrote last Saturday, the one that few people read carefully, understanding what was going on.

This is not a new bug, it exists, and I knew it, since 2004 or before, when banks did not use security checks, yet.

Kind Regards, and please choose another browser until Microsoft will not fix this problem for every IE.

Monday, September 08, 2008

Internet Explorer 6, 7, or 8 exposes users data via JavaScript

Ok, ok, I know these are Google Chrome dedicated days, but how can be possible that my last post did not receive attention at all?

Maybe with this title somebody will read more carefully what I wrote few days ago ... or maybe not, who knows? :?

Thursday, September 04, 2008

Security Basis, and an Internet Explorer data stealer

It has been about 4 years, or more, that I know about this problem, but for some reason I did not talk about it, scared by possible reactions.

In other words, I was waiting for some noise over the net, or some fix from Microsoft, but nothing is happening.

Actually, Microsoft is working hard on Internet Explorer 8, but the problem I am talking about, is still present ... so, I suppose it is time to tell you how dangerous this IE "feature" could be, and how dangerous could be to forget a little detail in a form, like the autocomplete attribute.

The magic autocomplete option


Every browser tries to make our net life as simple as possible, and when we start inserting data in an input field, it suggests us a couple of words or, if the name of that field is unique enough, directly the most probable word, name, or number, we are going to insert.
To perform this operation, we could start typing the name, or simply use the down arrow button to open the list of options, and choose, usually, the first one.

More magic than ever


In some old Internet Explorer versions, like the the 6th one, when we are filling out a login form, we simply need to insert the name, or email, and the password field will be magically populated.
This means that with 3 buttons, 2 down arrows, and 1 enter, we can perform a login.

Magic IE JavaScript


Internet Explorer allows JavaScript developers to fire events simulating user mode.
This means that if we have a focus on an input field, and we fire the keydown event, with down arrow code, the suggested list of options will magically appear.
At the same time, if we repeat the procedure, the first option is highlighted, and if we repeat the procedure again, the second option and so the third one, if any.
More beautiful, is that if we fire the event another time, this time using the enter code, the field will be populated.

How to steal information from the Internet Explorer users


Accordingly, if a malicious website is replicating a form, which user has filled out ones on a genuine website and a dedicated JavaScript starts automatically interacting with the replicated form, the Internet Explorer will silently expose user's information, previously used in "who knows" how many different websites.
A simple, well organized process could try different combinations N times, saving results in an object, or an array, and then sending that information via ajax or a basic get request to a server, allowing the malicious developer to save and reuse that information.

A real world example


To show you what I am talking about, I have created a simplified version of the described script.
Most important things to remember:

  • any displayed information, if any, will not be saved, but only displayed in an alert window, so with my example your data is still your one

  • only Internet Explorer, as far as I know, allows JS developers to create such malicious code to embed in a webpage (that's why I posted about FireFox crash, few days ago :))

  • apparently, IE8, and probably 7 too, do not let developers steal entire login information


To perform this test, you need to use Internet Explorer. If you have never used, or used it only to debug or develop some web applications, please try to login into your favourite web services, for example Gmail.
After that you can directly test my safe example page, and wait few seconds to know if my application was able to get your email account, or whatever else information.

Which websites expose user information?


I am sure this problem is not a secret for Microsoft IE Team, since in every login form, starting from hotmail, they force the atocomplete option to off.
Therefore, it is not possible to steal, for example, hotmail emails, but if you use the same address to login in to another website, which for some reason does not implement the autocomplete off option, it becomes obvious how thousands of spammers can obtain our email addresses in such an easy way.
Gmail login service (surprise!) does not implement the autocomplete off option, so if we use Internet Explorer to login into latter service, our Gmail account name could be easily exposed.
The worst case scenario ever, is represented by Credit Card Forms, where if nobody though about this "little security problem", our Account Name, Credit Card, Verification Code, and whatever else private information, could be grabbed by malicious websites, without us noticing it.
Of course, the expiration date is not that simple to retrieve, but what a powerful weapon this IE feature can be to enhance phishing?
Just try to imagine a page, with similar URL, that already contains all information, but misses only the expiration date, requiring user verification.

As Summary


Other browsers probably know about this problem, since nobody lets JavaScript interact with webpages in the real user mode.
The fix I can simply suggest, is to disable the autocomplete option in Internet Explorer or, even better, change the browser to be sure that if we are inputting our details on a website, that information will not be readable from any other website without our authorization.

Have a nice week end :P

Tuesday, September 02, 2008

Google Chrome Fix

Update 2008/09/04
I have created a new version that should be able to recognise the correct Google directory in every supported windows, and not only English version.

Please do not hesitate to tell me if the created link for No Sandbox Option is not creating it properly, thank you.

Google Chrome Fix Multi Language OS
-----------------------

I successfully tested the new browser in my laptop, while today I had some headache at work.

This is the reason I created in few minutes a simple Windows Application that let you choose which option you want to solve crashes during Google Chrome startup:

The application failed to initialize properly (0x00000005). Press Ok to terminate application.


Please note that the registry fix option changes a key that should solve Symantec problems, but it is not clear if this key could change security level for those PC that use Symantec end point protection, or similar softwares.

In every other case, the GUI create a link to launch Chrome without multiple sandbox, and if I am not wrong, it should mean that multi tab will not be multi thread.

Here you can find the project page, where there is a download section and an executable file.

Thanks to AutoIt developers, and ~d-bliss for the icon.

Enjoy :)

Thursday, August 28, 2008

IE8 Beta 2 - inline images, and anything else

With IE8, we finally can "play" with inline images, specially for CSS or other little decorations.

The main limitation is that the length of the data protocol has a maximum fixed length, but even worst is that IE8 apparently introduced the data protocol only for images.

In another scenario,where we would like to use the same technique for other purposes, IE is still the only browser that does not respect standards.

This is an example:

function evalazy(src, callback){
var script = document.createElement("script"),
body = document.documentElement;
if(callback)
script.onload = callback;
script.type = "application/javascript";
script.src = "data:" + script.type + "," + encodeURIComponent(src);
body.removeChild(body.appendChild(script));
};

Above function is able to evaluate valid JavaScript code in an asynchronous way, calling a callback, if any, when evaluation has been completed ( kinda load runtime an external script ).

Since functions like atob and btoa are still not standard, the script is evaluated as url encoded string.
But even using a base64 string, the result does not change, IE does nothing, or it could generates an error, the classic could not complete the operation due to error 800a03e8 if the body is not present, and in some case, it could even crash during next script execution.

evalazy("testMe = 123", function(){
alert(testMe);
});


In this case the problem is JavaScript, but since the data protocol has been only partially implemented, we will not be able to include every other kind of resource that is not an image.

Hoping I am wrong, and hoping they'll make data protocol more "efficient", let's play with IE8 and its new features, really, and generally, appreciated. Thanks IE8 team :)

Thursday, August 21, 2008

How to crash FireFox 3 with 3 lines of code

Hi there, here I am back from holidays :geek:

Before I'll start to write more interesting stuff, here we have 3 lines of JavaScript that could cause problems to our favourite browser, in this case version 3.0.1

I discovered this problem, already part of the bugs report site, trying to emulate keyboards events using the UIEvents interface instead of KeyboardEvents


var e = document.createEvent("UIEvents");
e.initUIEvent("keypress", true, true, this, 1);
document.documentElement.dispatchEvent(e);


Nice one? See you soon ;)

Tuesday, August 05, 2008

Image Protector, a nice waste of time

I've read right now about another, pointless, attempt, to avoid the classic Save Image As from a website.

Guys, we are in 2008, and I hope that everybody knows what can the simple Stamp / Print button can do, when we are simply watching whatever in our screen.

No way, every tot months, somebody "creates" the ultimate version of an Image Protector, usually based on JavaScript, then "startly pointless" because JS could be easily disabled.

Morevore, this times the trickless trick even requires an excellent library as MooTools is.

Well, since I hate disinformations about techniques to make data truly safe, I can tell you that you need 159 characters to remove the protecion, javascript protocol included.

The funny stuff is that basing the same anti protector over MooTools, since this library is required for the amazing protector, you need even less characters to do the same, basing them on a $$("img") call, instead of document.getElementsByTagName.

Being sure that this technique will be probably adopted from people that do not know a single thing about web or security, and do not know how to implement a basic Watermark, I suppose somebody will implement the same trickless trick, so I prefer to show you the extended link that, if saved in your bookemark, will be able to remove the protection whenever you need, and in a click.

This is the code:

javascript:(function(b,r,l){l=b.length;while(0<l--)r.test(b[l].src)&&b[l].parentNode.removeChild(b[l--]);})(document.getElementsByTagName("img"),/blank\.gif$/);


And this is the link:
noMooreProtection

Save into bookmark, drag there, try the example page, one click in the "bookmarked magic guru crack", and sweat dreams, you can still grab images from those sites that do not have a clue about safe contents :D