Inject javascript into a javascript function

前端 未结 7 1793
别跟我提以往
别跟我提以往 2021-02-04 13:25

I\'ve got a weird question in that I need to inject some javascript into another javascript function. I am using a framework which is locked so I can not change the existing fun

7条回答
  •  南方客
    南方客 (楼主)
    2021-02-04 13:51

    function doSomething() { ... }
    var oldVersionOfFunc = doSomething;
    doSomething = function() {
        var retVal = oldVersionOfFunc.apply(oldVersionOfFunc, args);
        // your added code here
        return retVal;
    }
    

    This seems to provoke an error (Too much recursion)

    function doSomething(){ document.write('Test'); return 45; } 
    var code = 'myDoSomething = ' + doSomething + '; function doSomething() { var id = myDoSomething(); document.write("Test 2"); return id; }';
    eval(code)
    doSomething();
    

    This works for me, even if it is ugly.

提交回复
热议问题