paulbartrum / jurassic

A .NET library to parse and execute JavaScript code.
MIT License
868 stars 121 forks source link

ScriptEngine.GetGlobalValue #217

Closed ertant closed 2 years ago

ertant commented 2 years ago

Hi, ScriptEngine.GetGlobalValue method throws an JavaScriptException instead of null value for undefined values. I'm not sure is this normal but GetGlobalValue method documentation says "The value of the global variable, or null otherwise."

In method TypeConverter.ToObject(ScriptEngine engine, Object value) value is set to Undefined.Value.

Exception stack.

object at Jurassic.TypeConverter.ToObject(ScriptEngine engine, Object value, Int32 lineNumber, String sourcePath, String functionName) at Jurassic.TypeConverter.ToObject(ScriptEngine engine, Object value) at Jurassic.TypeConverter.ConvertTo(ScriptEngine engine, Object value, Type type) at Jurassic.TypeConverter.ConvertTo[T](ScriptEngine engine, Object value) at Jurassic.ScriptEngine.GetGlobalValue[T](String variableName)

Workaround;

Calling Engine.GetGlobalValue("foo") as T resolves the problem instead of using the Engine.GetGlobalValue("foo")

paulbartrum commented 2 years ago

The doc comment is wrong, GetGlobalValue() never returns null. It normally won't throw though. The only time it should throw is if you call GetGlobalValue<ObjectInstance>() since undefined cannot be converted to an object (whereas it can be converted to a boolean, number or string).