扩展activxobject的方法

http://stackoverflow.com/questions/797960/extending-an-activexobject-in-javascript

You can in fact override ActiveXObject().

This means you can try to build a transparent proxy object around the actual object and hook on method calls. This would mean you'd have to build a proxy around every method and property your ActiveX object has, unless you are absolutely sure there is no code whatsoever calling a particular method or property.

I've built a small wrapper for the "MSXML2.XMLHTTP" object. There are probably all kinds of problems you can run into, so take that with a grain of salt:

varActualActiveXObject=ActiveXObject;varActiveXObject=function(progid){var ax =newActualActiveXObject(progid);if(progid.toLowerCase()=="msxml2.xmlhttp"){var o ={
      _ax: ax,
      _status:"fake",
      responseText:"",
      responseXml:null,
      readyState:0,
      status:0,
      statusText:0,
      onReadyStateChange:null// add the other properties...};
    o._onReadyStateChange =function(){varself= o;returnfunction(){self.readyState   =self._ax.readyState;self.responseText =self._ax.responseText;self.responseXml  =self._ax.responseXml;self.status       =self._ax.status;self.statusText   =self._ax.statusText;if(self.onReadyStateChange)self.onReadyStateChange();}}();
    o.open =function(bstrMethod, bstrUrl, varAsync, bstrUser, bstrPassword){
      varAsync =(varAsync !==false);this._ax.onReadyStateChange =this._onReadyStateChange
      returnthis._ax.open(bstrMethod, bstrUrl, varAsync, bstrUser, bstrPassword);};
    o.send =function(varBody){returnthis._ax.send(varBody);};// add the other methods...}else{var o = ax;}return o;}functionTest(){var r =newActiveXObject('Msxml2.XMLHTTP');

  alert(r._status);// "fake"

  r.onReadyStateChange =function(){ alert(this.readyState);};
  r.open("GET","z.xml");
  r.send();

  alert(r.responseText);}

Disclaimer: Especially the async/onReadyStateChange handling probably isn't right, and the code may have other issues as well. As I said, it's just an idea. Handle with care.

P.S.: A COM object is case-insensitive when it comes to method- and property names. This wrapper is (as all JavaScript) case-sensitive. For example, if your code happens to call both "Send()" and"send()", you will need a skeleton "Send()" method in the wrapper as well:

o.Send=function(){returnthis.send.apply(this, arguments);};
posted on 2013-06-14 21:44  tanglaoya321  阅读(150)  评论(0)    收藏  举报