I'm currently using the Jint.NET JavaScript console engine for C#, and I'm attempting to emulate separate JavaScript environments that the user can switch between.
However, I don't want to create an entirely new console engine for each JavaScript environment and cause a large overhead, instead just switch between them using a single engine and store the environments somewhere else, eg:
engine 1
| |
| |
env 1 env 2
Is it possible to do this?
Found a solution to this, although there's no documentation for this anywhere that I can find, so this may be an unintended method. You need to use EnterExecutionContext
on newly created LexicalEnvironments
, and you can switch between them to have separate JS environments.
Here's an example:
using Jint.Runtime.Environments;
using Jint.Native.Object;
using Jint.Native.Global;
//Create a new object instance and environment.
JSObjectInstance = GlobalObject.CreateGlobalObject(jintEngine);
JSEnvironment = LexicalEnvironment.NewObjectEnvironment(jintEngine, JSObjectInstance, jintEngine.GlobalEnvironment, false);
//Enter the new environment.
jintEngine.EnterExecutionContext(JSEnvironment, JSEnvironment, new Jint.Native.JsValue(false));
And when you're done with that environment, you can leave using LeaveExecutionContext
, and rejoin the default global one like so:
jintEngine.EnterExecutionContext(jintEngine.GlobalEnvironment, jintEngine.GlobalEnvironment, jintEngine.Global);