Inject javascript into a javascript function

前端 未结 7 1801
别跟我提以往
别跟我提以往 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:50

    Alias it.

    var oldDoSomething = doSomething;
    doSomething = function() {
      // Do what you need to do.
      return oldDoSomething.apply(oldDoSomething, arguments);
    }
    
    0 讨论(0)
  • 2021-02-04 13:50

    I can not change the doSomething function... Instead I need to somehow inject a few lines of code into the end of the doSomething code

    Injecting a few lines into the end of the doSomething code sounds like changing the doSomething function, to me. I think, unfortunately, that you’re screwed.

    (I’m a bit hazy on all this, but I think functions are how people who worry about such things implement information hiding in JavaScript, precisely because you can’t access their scope from outside them.)

    0 讨论(0)
  • 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.

    0 讨论(0)
  • Thanks for all your feedback. Each answer gave me a clue and as such I've come up with the following solution.

    <body>
    <script type="text/javascript">
        var val;
        function doSomething(item1, item2) {
            var id = 3;
        }
        function merge() {
            var oScript = document.createElement("script");
            var oldDoSomething = doSomething.toString();
            oScript.language = "javascript";
            oScript.type = "text/javascript";
            var args = oldDoSomething.substring(oldDoSomething.indexOf("(") + 1, oldDoSomething.indexOf(")"));
            var scr = oldDoSomething.substring(oldDoSomething.indexOf("{") + 1, oldDoSomething.lastIndexOf("}") - 1);
            var newScript = "function doSomething(" + args + "){" + scr + " val = id; }";
            oScript.text = newScript;
            document.getElementsByTagName('BODY').item(0).appendChild(oScript);
        }
    
        merge();
    
    </script>
    <input type="button" onclick="doSomething();alert(val);" value="xx" />
    

    0 讨论(0)
  • 2021-02-04 14:04

    Altering the function by working with the source code strings can be quite simple. To do it for a specific instance, try:

    eval(doSomething.toString().replace(/}\s*$/, ' return id; $&'));
    

    Now doSomething returns the ID. I'm not normally a fan of eval, but normal aspect oriented programming techniques don't apply here, due to the requirement for accessing a local variable.

    If doSomething already returns a value, try wrapping the body in a try ... finally:

    eval(doSomething.toString()
        .replace(/^function *\w* *\([^)]*\) *{/, '$& try {')
        .replace(/}\s*$/, '} finally { window.someID = id; } $&')
    );
    

    To turn this into a function, we need to make the code evaluate in global scope. Originally, this answer made use of with to change the scope of the eval, but this doesn't currently work in browsers. Instead, .call is used to change the scope of eval to window.

    (function () {
        var begin = /^function\s*\w*\s*\([^)]*\)\s*{/,
            end = /}\s*$/;
    
        function alter(func, replacer) {
            var newFunc = replacer(func.toString());
            eval.call(window, newFunc);
        }
    
        function insertCode(func, replacer, pattern) {
            alter(func, function (source) { 
                return source.replace(pattern, replacer);
            });
        };
    
        /* Note: explicit `window` to mark these as globals */
        window.before = function (func, code) {
            return insertCode(func, '$& ' + code, begin);
        };
    
        window.after = function (func, code) {
            return insertCode(func, code + ' $&', end);
        };
    
        window.around = function (func, pre, post) {
            /* Can't simply call `before` and `after`, as a partial code insertion may produce a syntax error. */
            alter(func, function(source) {
                return source
                    .replace(begin, '$& ' + pre)
                    .replace(end, post + ' $&');
            });
        };
    })();
    ...
    after(doSomething, 'return id;');
    /* or */
    around(doSomething, 'try {', '} finally { window.someID = id; }');
    

    If you want to rewrite methods and anonymous functions bound to variables, change alter to:

    ...
        function alter(func, replacer) {
            var newFunc = replacer(eval('window.' + funcName).toString());
            eval.call(window, newFunc);
        }
    ...
    function Foo() {}
    Foo.prototype.bar = function () { var secret=0x09F91102; }
    ...
    after('Foo.prototype.bar', 'return secret;');
    

    Note the first argument to the functions are now strings. Further improvements could be made to handle methods that aren't accessible in global scope.

    0 讨论(0)
  • 2021-02-04 14:05

    Functions are first class values in Javascript, which means that you can store them in variables (and in fact, declaring a named function is essentially assigning an anonymous function to a variable).

    You should be able to do something like this:

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

    (But, I could be wrong. My javascript's a little rusty. ;))

    0 讨论(0)
提交回复
热议问题