0

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?

Larry Tang
  • 642
  • 5
  • 23
  • Perhaps: Could swap in/out global’s properties AND run user code inside an (anonymous) function to avoid global-scope pollution. Not full isolation. – user2864740 Sep 20 '19 at 21:54

1 Answers1

1

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);
Larry Tang
  • 642
  • 5
  • 23