Call JavaScript from C#

Evaluating JavaScript hosted in a WebView

PDF for offline use
Sample Code:
Related Articles:
Related APIs:

Let us know how you feel about this

Translation Quality


0/250

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

Overview

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, see WebView.

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.

Xamarin Workbook

If it's not already installed, install the Xamarin Workbooks app first. The workbook file should download automatically, but if it doesn't, just click to start the workbook download manually.