分析js代碼的運行路徑

隻是個最基礎的想法瞭。具體的實踐稍微復雜一些:
1 如果script是用src引入的,還要用xhr或者json方式來獲得text,可能還需要搭個後臺代理。
2 如果function是在命名空間的,可以直接遞歸for in命名空間去挖裡面的public函數出來。
3 private的函數我看就算瞭,私有函數應該對自己負責,我們沒有必要非去整人傢的私貨。



<HTML>
<BODY>
<SCRIPT LANGUAGE=”JavaScript”>
<!–
function a(x,y,z){return b(x,y)*c(z)};
function b(x,y){return c(x)*c(y)};
function c(x){return x+x};



setTimeout(“alert(a(1,2,3))”,0)
//–>
</SCRIPT>
<SCRIPT LANGUAGE=”JavaScript”>
<!–
(function (){
    window._log=[];
    function obj2str(o){
        var r = [];
        if(typeof o ==”string”) return “””+o.replace(/([\”\])/g,”\$1″).replace(/(
)/g,”\n”).replace(/()/g,”\r”).replace(/( )/g,”\t”)+”””;
        if(typeof o ==”undefined”) return “undefined”;
        if(typeof o == “object”){
            if(o===null) return “null”;
            else if(!o.length){
                for(var i in o)
                    r.push(i+”:”+obj2str(o[i]))
                r=”{“+r.join()+”}”
            }else{
                for(var i =0;i<o.length;i++)
                    r.push(obj2str(o[i]))
                r=”[“+r.join()+”]”
            }
            return r;
        }
        return o.toString();
    }


    function log(s){
        _log.push(s);
    }
    var s=document.getElementsByTagName(“SCRIPT”)[0].text;
    var r=/function (w+)(/g;
    var fns=s.match(r);
    for(var i=0;i<fns.length;i++){
        fn=fns[i].replace(r,”$1″)
        if (typeof window[fn]==”function”){
            window[fn]=(function(org,fn){
                return function(){
                    log(“進入:”+fn+”
調用參數:”+obj2str(arguments));
                    var r=org.apply(null,arguments);
                    log(“退出:”+fn+”
返回值”+obj2str(r));
                    return r
                }
            })(window[fn],fn)
        }
    }
})()
setTimeout(“alert(window._log.join(\n\n))”,100)
//–>
</SCRIPT>
</BODY>
</HTML>

You May Also Like