microsoft / ClearScript

A library for adding scripting to .NET applications. Supports V8 (Windows, Linux, macOS) and JScript/VBScript (Windows).
https://microsoft.github.io/ClearScript/
MIT License
1.74k stars 148 forks source link

Don't expose System.Object public members to the script? #451

Closed iotalambda closed 1 year ago

iotalambda commented 1 year ago

How can we provide a host object to the engine in such a way, that System.Object's public members (properties, methods) would not be exposed to the script?

For example, if we do engine.AddHostObject("console", new { log = new Action<string>(Console.WriteLine) }); then the console object and its console.log property will have GetHashCode etc. exposed.

I tried using PropertyBag like engine.AddHostObject("console", new PropertyBag { ["log"] = new Action<string>(Console.WriteLine) }); but still, the problem persists with console.log. Perhaps there's something PropertyBag-like for functions?

ClearScriptLib commented 1 year ago

Hi @iotalambda,

You can do something like this:

dynamic setupConsole = engine.Evaluate("impl => console = { log: arg => impl.WriteLine(arg) }");
setupConsole(typeof(Console).ToHostType(engine));

This way console.log is a normal JavaScript function, and the underlying System.Console host type is inaccessible.

Good luck!

iotalambda commented 1 year ago

Hi @ClearScriptLib ,

Oh yes, this solves the problem elegantly :) Thanks!