duonglaiquang · GitHub

This is an issue and fix for org.mozilla.javascript.NativeReflect, the class in htmlunit-rhino-fork that hasn't yet reached upstream.

Problem in brief

Attempting to call the JS method Reflect.apply() with a primitive value for thisArgument throws TypeError: Method called on incompatible object in HtmlUnit 3.5.0.

According to the specs, primitive values need to be converted to objects.

Reproducing

Here's an example to reproduce:

// Expected: To output "foo"
// Actual: Throws TypeError: Method "toString" called on incompatible object (...)
console.log(Reflect.apply(String.prototype.toString, "foo", []));

Incidentally, calling the method directly works as expected:

// Outputs: "foo"
console.log(String.prototype.toString.apply("foo", []));

Suggested fix

Add support to the code handling args[1]:

         Scriptable callable = ScriptableObject.ensureScriptable(args[0]);
-        if (args[1] instanceof Scriptable) {
+        if (ScriptRuntime.isPrimitive(args[1])) {
+            thisObj = cx.newObject(scope, "Object", new Object[] {args[1]});
+        } else if (args[1] instanceof Scriptable) {
             thisObj = (Scriptable) args[1];
         }

Read the original on github.com ↗