Page 1 of 1

pass values between C# and JavaScript

Posted: Sun Feb 07, 2016 8:28 am
by rkmore
I have successfully injected some javascript using the JSIL.Verbatim mechanism (see below) but what I can't quite figure out is how to pass values back and forth between the two.

Can anyone tell me how to do this? Are there any additional samples of examples that maybe I am overlooking?

Code: Select all

        private void gpsButton_Click(object sender, RoutedEventArgs e)
        {
            if (CSharpXamlForHtml5.Environment.IsRunningInJavaScript)
            {
                //how do I get value or lat and lon from
                JSIL.Verbatim.Expression(@"
function getLocation()
{
    if (navigator.geolocation)
    {
        navigator.geolocation.getCurrentPosition(showPosition);
    }
}
function showPosition(position)
{
    alert(""Latitude: "" + position.coords.latitude +  ""   Longitude: "" + position.coords.longitude);
}
getLocation();");
            }
            else
            {
                gpsValue.Text = "Cannot run script in simulator.";
            }

        }

Re: pass values between C# and JavaScript

Posted: Sun Feb 07, 2016 1:02 pm
by rkmore
So I found a way that works, but it seems very clunky. Anyone know a cleverer way to do this:

Code: Select all


        void GetLocation()
        {
            gMainPage = this;
            JSIL.Verbatim.Expression(
                @"navigator.geolocation.getCurrentPosition($0);",
                (Action<dynamic>)GpsReceived);
        }

        static MainPage gMainPage = null;
        static void GpsReceived(dynamic eventArgs)
        {
            double glat = 0;
            double glon = 0;
            glat = (double)eventArgs.coords.latitude;
            glon = (double)eventArgs.coords.longitude;
            gMainPage.ShowLatLon(glat, glon);
        }

        public void ShowLatLon(double glat, double glon)
        {
            gpsValue.Text = "Lat: " + glat.ToString() + ",  Lon: " + glon.ToString();
        }