microsoft / ClearScript

A library for adding scripting to .NET applications. Supports V8 (Windows, Linux, macOS) and JScript/VBScript (Windows).
https://microsoft.github.io/ClearScript/
MIT License
1.74k stars 148 forks source link

fetch - How should JSON objects be passed into JavaScript #546

Closed kissxrl closed 10 months ago

kissxrl commented 10 months ago

535

I am currently using ethers and using it in v8, but ethers will use fetch

How to implement fetch in C # when accessing the network

using var engine = new V8ScriptEngine(V8ScriptEngineFlags.EnableTaskPromiseConversion);
engine.AddHostObject("fetch", Response.fetch);

public sealed class Response {
    private string _html;
    public Task<string> text() => Task.FromResult(_html);
    public static async Task<Response> fetch(string url, IScriptObject obj = null){
        if (obj != null) ...............
        using var client = new HttpClient();
        return new Response { _html = await client.GetStringAsync(url) };
    }
}

I added a method, but JavaScript cannot recognize this object

public Task<object> json()
{
        var jsonObject = Newtonsoft.Json.JsonConvert.DeserializeObject(_html);
        return Task.FromResult(jsonObject);
}
ClearScriptLib commented 10 months ago

Hi @kissxrl,

Try something like this:

public Task<object> json() => Task.FromResult<object>(ScriptEngine.Current.Script.JSON.parse(_html));

Good luck!

ClearScriptLib commented 10 months ago

Please reopen this issue if you have additional thoughts or questions about this topic. Thanks!