Find file History
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
..
Failed to load latest commit information.
CallJavaScript reorganizing forms recipes Mar 12, 2018
README.md adding absolute link to guides Mar 29, 2018

README.md

id title subtitle brief article api
1FD0ABA3-95A1-4830-B279-36CDB7E2B5AD
Call JavaScript from C#
Evaluating JavaScript hosted in a WebView
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.