skip to Main Content

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:

  • Map.xaml; contains my webview
  • Map.xaml.cs; set image in the map and get values from my webview
  • Map.html; Leaflet and all map functionalities

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.

2

Answers


  1. Chosen as BEST ANSWER

    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.


  2. After my testing, you can try changing the code you provided to:

    string deleteMarkerData = await webView.EvaluateJavaScriptAsync("document.getElementById('deleteMarkerData').innerHTML");
    

    By changing .value to .innerHTML, deleteMarkerData can correctly get the value.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search