Quantcast
Channel: ClearScript
Viewing all articles
Browse latest Browse all 2297

New Post: Evaluating CLR Method as value in script

0
0
Hi krisoye

Is there a way to override the toString() method on ClearScript objects? Perhaps via some sort of Prototype object? [...] Expected: Something other than undefined and ideally overridden to "function getElementsByClassName() { [native code] }"

Installing a custom toString method for host objects is quite simple. However, producing special output specifically for host methods is a bit tricky because the managed type that represents host methods is internal to ClearScript.

Nevertheless, it can be done with a bit of trickery. Here's a code sample that replaces the built-in toString method for host objects with a function that produces the desired output for host methods:
dynamic setup = engine.Evaluate(@"
    (function (obj, func) {
        obj.constructor.prototype.toString = function() { return func(this); }
    }).valueOf();
");

setup(newobject(), new Func<object, string>(obj => {
    var str = obj.ToString();
    if (obj.GetType().FullName == "Microsoft.ClearScript.HostMethod") {
        return"function " + str.Substring(11) + "() { [native code] }";
    }
    return str;
}));
Clearly this is quite hacky and may not work in the future, but hopefully it can provide a quick fix.

Good luck!

Viewing all articles
Browse latest Browse all 2297

Latest Images

Trending Articles





Latest Images