Adding objects to a ShadowRealm #1609
-
After reading through #789 I've been trying to set up a shadow realm to use as an isolated context. It looks like it could work, but I don't see an easy way to dynamically add objects from C#. // manually writing the object works as expected
var engine = new Engine();
var sr = engine.Realm.Intrinsics.ShadowRealm.Construct();
sr.Evaluate("var obj = { prop: 100 };");
sr.Evaluate("obj.prop + 100"); // output: 200 - expected
engine.Evaluate("obj.prop + 100"); // error: obj is not defined - expected What I've tried: // JsObject.ToString() doesn't serialize the object to JSON.
sr.Evaluate($"var obj = {JsObject.FromObject(sr.Engine, new { prop = 100 })};"); // error: unexpected token // value passing between realms must be callable or primitive
var func = sr.Evaluate("(obj) => obj.prop + 100");
Engine.Invoke(func, new { Prop = 1 }); // error: result is not callable - sort of expected // this just sets a prop on the ShadowRealm object itself
sr.Set("obj", JsValue.FromObject(sr.Engine, new { prop = 100 }));
sr.Evaluate("obj.prop + 100"); // error: obj is not defined - expected
engine.Evaluate("obj.prop + 100"); // error: obj is not defined - expected // both of these set the value in the global realm not the shadow realm
sr.Engine.SetValue("obj", new { prop = 100 });
sr.Engine.Realm.GlobalObject.Set("obj", JsValue.FromObject(sr.Engine, new { prop = 100 }));
sr.Evaluate("obj.prop + 100"); // Cross-Realm Error: obj is not defined
engine.Evaluate("obj.prop + 100"); // output: 200 A work around is either manually serializing the object with Json.NET, System.Text.Json, etc. -- or reflecting the internal realm from the ShadowRealm and setting the global state of that: var realm = (Realm) sr.GetType().GetField("_shadowRealm", BindingFlags.NonPublic | BindingFlags.Instance)!.GetValue(sr);
realm.GlobalObject.Set("obj", JsValue.FromObject(sr.Engine, new { prop = 100 }));
sr.Evaluate("obj.prop + 100"); // output: 200 - works
engine.Evaluate("obj.prop + 100"); // error: obj is not defined - expected Question Request |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Seems that you are after #1573 |
Beta Was this translation helpful? Give feedback.
Seems that you are after #1573