The following tutorial will show to call a JavaScript function from C#, where the JavaScript function is defined in a web page hosted by the WebView
control.
Calling JavaScript
The following code 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>