Alex Rivera | Logout

How override eval function in javascript?

Asked 2010-04-02T13:52:01.420
10

For example:

(function() {
      var proxied = window.eval;
      window.eval = function() {
        return proxied.apply(this, arguments);
      };
    })();

But this code is not working.

Edit
Report

1 Answer

6

Although not portable, the following approach works in some places where it otherwise wouldn't (as it satisfies ES5's requirements that A) it be retrieved as a Reference in a MemberExpression, not a Value and B) it results in the ‘standard builtin function.’ — ES5 #15.1.2)

(function() {
  var proxied = window.eval
  with({get eval(){ console.log('eval called'); return proxied }}) {
    /* client code */
  }
})()

This obviously only applies if you can wrap the client code in a with() statement; though in many situations, that shouldn't be hard. Obviously, the same approach can shadow window with another object with all of its' properties, and a getter-proxied eval.

Environments that don't support SpiderMonkey's get statement, may be able to use ES5's defineProperty. Look into that yourself.

answered 2012-11-20T08:27:34.483

Your Answer