AngleSharp / AngleSharp.Js

:angel: Extends AngleSharp with a .NET-based JavaScript engine.
https://anglesharp.github.io
MIT License
103 stars 22 forks source link

JavaScript exception when trying to call JavaScript function from C# code with Invoke, passing in element node created in C# #76

Open martin-honnen opened 3 years ago

martin-honnen commented 3 years ago

Bug Report

Prerequisites

For more information, see the CONTRIBUTING guide.

Description

[Description of the bug]

I get a JavaScript exception in a sample trying to Invoke a JavaScript function from C# code, passing in an element node created on the C# side of the code.

Steps to Reproduce

  1. [First Step] Run the code
    
    using System;
    using System.Threading.Tasks;
    using AngleSharp;
    using AngleSharp.Scripting;
    using Jint.Native;

namespace JavaScriptExceptionMWE { class Program { static async Task Main() { var jsService = new JsScriptingService();

        var config = Configuration.Default.With(jsService);

        var context = BrowsingContext.New(config);

        var source = "<!DOCTYPE html><html><head><title>Test</title><script>function f1(el) { document.body.appendChild(el); }</script></head><body><h1>Some example source</h1><p>This is a paragraph element.</p></body></html>";

        var document = await context.OpenAsync(req => req.Content(source));

        Console.WriteLine("Serializing the (original) document:");
        Console.WriteLine(document.DocumentElement.OuterHtml);

        var f1 = jsService.GetOrCreateJint(document).GetValue("f1");

        var sectionElement = document.CreateElement("section");
        sectionElement.TextContent = "This is a section.";

        var jsSectionElement = JsValue.FromObject(jsService.GetOrCreateJint(document), sectionElement);

        f1.Invoke(jsSectionElement);

        Console.WriteLine("Serializing the document again:");
        Console.WriteLine(document.DocumentElement.OuterHtml);
    }
}

}


**Expected behavior:** On the `f1.Invoke(jsSectionElement);` call, I get an exception 

Jint.Runtime.JavaScriptException HResult=0x80131500 Message= Source=jint StackTrace: at Jint.Native.Function.ScriptFunctionInstance.Call(JsValue thisArg, JsValue[] arguments) at Jint.Native.JsValue.Invoke(JsValue thisObj, JsValue[] arguments) at Jint.Native.JsValue.Invoke(JsValue[] arguments) at JavaScriptExceptionMWE.Program.

d__0.MoveNext() in C:\Users\marti\source\repos\JavaScriptExceptionMWE\Program.cs:line 33



**Actual behavior:** I would expect the code to run without throwing any error and the C# created element to be appended as  a child of the HTML's body element so that the final `Console.WriteLine(document.DocumentElement.OuterHtml);` would show `<section>This is a section.</section>` as the last child of the `body` element.

**Environment details:** [OS, .NET Runtime, ...] Windows 10 20H2, .NET 5 (Core) VS 2019 console project

## Possible Solution

[Optionally, share your idea to fix the issue]