Tuesday, June 7, 2011

Overriding/Wrapping/Extending ActiveX and XMLHttpRequest object

Sometimes a special or a custom behaviour may be desired whenever an Ajax call is made from the Javascript code in the page.

In Internet Explorer 6 and earlier, XMLHTTP was implemented as an ActiveX object provided by Microsoft XML (MSXML). Beginning with Internet Explorer 7, XMLHTTP is also exposed as a native scripting object.

The native implementation of the XMLHTTP object is designed with cross-browser compatibility in mind. With just a bit of script, it is easy to build a function that works with either version of Internet Explorer, or any browser that supports XMLHTTP
Also it is more efficient to create a native scriptable object than to create an ActiveX object.

var xmlHttp = null;
if (window.XMLHttpRequest) {
// If IE7, Mozilla, Safari, and so on: Use native object.
xmlHttp = new XMLHttpRequest();
}
else
{
if (window.ActiveXObject) {
// ...otherwise, use the ActiveX control for IE5.x and IE6.
xmlHttp = new ActiveXObject('MSXML2.XMLHTTP.3.0');
//Msxml2.XMLHTTP.6.0 ; Msxml2.XMLHTTP.3.0 ; Microsoft.XMLHTTP
}

Overriding ActiveX object: Following link gives the details of overriding Activex object:-
http://stackoverflow.mobi/question797960_Extending-an-ActiveXObject-in-javascript.aspx


The code first stores the instance of the actual ActiveXObject in a variable ActualActiveXObject.
Then the actual ActiveXObject's constructor is overridden with a custom constructor.
The custom constructor creates an instance of the Actual (or the overriden) Activex object.


If the arguement passed to constructor is not "msxml2.xmlhttp", then the instance of the actual Activex object is returned; Else, the rest of the code in the custom constructor is executed which creates a custom object O with certain variables and functions like Open(), Send, ReadyStateChanged(), etc. These custom functions contain user code and eventually call the respective function of the actual instance of the ActiveXObject.



Overriding XMLHttpRequest object: It is on almost similar lines to above code.
The following link and comments in it give details on overriding XMLHttpRequest object.
http://stackoverflow.com/questions/3596583/javascript-detect-an-ajax-event
http://blog.monstuff.com/archives/000252.html

No comments:

Post a Comment