HisTech Up

Xamarin.Forms: Evaluating JavaScript hosted in a WebView

Introduction

user

Christian Hissibini

I am a Tech enthusiast who loves to blend Dev & Design on Web and Mobile Platforms. I am also a Windows Platform Dev MVP


LATEST POSTS

What are the differences between Data Mining, Machine Learning and Deep Learning? 11th February, 2018

What are the challenges of using Artificial Intelligence? 15th January, 2018

Mobile Development

Xamarin.Forms: Evaluating JavaScript hosted in a WebView

Posted on .

The Xamarin.Forms WebView control displays HTML and other web content in an app. Unlike Device.OpenUri, which takes the user to the web browser on the device, the WebView control displays the web content inside the app. For more information about the WebView control.

Calling JavaScript

The following code example shows how a JavaScript function can be invoked from C#:

void OnCallJavaScriptButtonClicked (object sender, EventArgs e)
{
  ...
  int number = int.Parse (numberEntry.Text);
  int end = int.Parse (stopEntry.Text);

  webView.Eval (string.Format ("printMultiplicationTable({0}, {1})", number, end));
}

The WebView.Eval method evaluates the JavaScript that’s specified as the method argument. In this example the printMultiplicationTable JavaScript function is invoked, which in turn displays a multiplication table for the passed parameters.

The printMultiplicationTable JavaScript function is defined in the local HTML file that the WebView control loads, as shown in the following code example:

<html>
<body>
<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<div id='multiplicationtable'></div>
<script type="text/javascript">
function printMultiplicationTable(num, stop)
{
    var number = parseInt(num);
    var stopNumber = parseInt(stop);

    $('#multiplicationtable').empty();
    for (var index = 1; index <= stopNumber; index++) {
        $('#multiplicationtable').append(number + ' x ' + index + " = " + number * index + '<br/>');
    }
}
</script>
</body>
</html>

Summary

This recipe showed how to call a JavaScript function from C#, where the JavaScript function is defined in a web page hosted by the WebView control.

profile

Christian Hissibini

I am a Tech enthusiast who loves to blend Dev & Design on Web and Mobile Platforms. I am also a Windows Platform Dev MVP

There are no comments.

Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

View Comments (0) ...
Navigation