javascriptc#htmlwebviewmaui

Pass data from html JS webview to C# in MAUI


I am currently working on a custom leaflet map that I load using a webview in my xaml where the user is able to perform several actions, such as adding and deleting existing markers. The problem I'm facing is the data passing part from this webview back to my C# code.

Structure:

I tried using hidden fields where I put the changes the user made. So whenever the user deleted an item, I put this item inside the DeletedMarkers hidden field. Then back in my xaml.cs, I use:

var deleteMarkerData = await webView.EvaluateJavaScriptAsync("document.getElementById('deleteMarkerData').value");

here I either get a empty value or the marker object I deleted. I keep looping this to check if there is something inside this object every 0.2 seconds. This works, and I get the object correctly without much noticable delay, but now I was wondering if there is any way to get this object from my webview to my xaml.cs in a more performance friendly way.

Any suggestions?

Edit I got the answer finally, see underneath.


Solution

  • For those who want to pass data from a webview to c# for example, you can do the following. I finally figured it out:

    Xaml

    <WebView Grid.Row="0" x:Name="webView" VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand" Navigating="OnNavigating"/>
    

    Xaml.cs or code-behind

    private void OnNavigating(object sender, WebNavigatingEventArgs e)
    {
        Uri uri = new Uri(e.Url);
        var queryParams = HttpUtility.ParseQueryString(uri.Query);
    
        // Check if the 'registrationId' query parameter exists
        string registrationId = queryParams.Get("registrationId");
    
        if (!string.IsNullOrEmpty(registrationId))
        {
            // Cancel the navigation
            e.Cancel = true;
        }
    }
    

    Javascript file

    window.location.href = `/someRandomPageDoesntMatter?registrationId=${deleteMarkerData}`;
    

    What i'm doing here is trying to navigate to some random page, where I put the parameters inside the url I want to sent. Then I catch the navigation using the Navigation property of the webview, get the parameters, and cancel the navigation. So this way, i can sent data from my webview (html, js) to my c# code.