Executing user's supplied Javascript code with two-way callbacks between .NET and Javascript in MAUI

138 Views Asked by At

I have an old Winforms app that loads a user's Javascript file with predefined function names and then calls those functions from C# code at specific events. Also, there are some Javascript methods defined that call C# methods from the user's code.

For example, when my C# code receives an event from a hardware device, it checks if the user's script contains a specific function name to handle this event and then calls it passing a custom entity with the event information. The user's Javascript function processes the event and returns a response which, in turn, gets processed by C# code and sent to another hardware device.

There are also a few custom Javascript functions available to the user for synthesizing new commands that get received by C# code and then sent to the device.

I am using Jint for this two-way communication. It was pretty easy and straightforward to register event handlers and add custom Javascript functions that call my C# methods for hardware:

jintEngine.SetValue("sendEventX", new Action<EventX>((x) =>
{
    outputDevice.Send(x.ConvertToOutputModel());
}));

...

inputDevice.OnEventY += (InputDevice sender, in EventYMessage e) =>
{
    if (!currentScript.Contains($" handleEventY"))
    {
        return;
    }
           
    var y = (EventY)js.Invoke("handleEventY", e).ToObject();

    if (y != null)
    {
        ... do stuff with y that was returned from the user's Javascript handleEventY function
    }
};

Now I'm considering porting my old Winforms app to MAUI to give it a more modern look and also to support macOS.

I'm wondering, is there any "out-of-the-box" way in MAUI to do the same thing as I did with Jint, or it would require ugly and inefficient solutions for communication through WebView? I need low latency for processing those hardware events, and thus far Jint has been good enough.

0

There are 0 best solutions below