在Xamarin中调用JavaScript函数

问题描述 投票:1回答:1

如何在Xamarin中调用JavaScript方法?我找到了对此(https://github.com/chkn/HybridKit)的库,但是不幸的是,该工具可以在JavaScript中调用C#函数。对于Xamarin.Forms,我找到了一个解决方案https://docs.microsoft.com/en-au/xamarin/xamarin-forms/app-fundamentals/custom-renderer/hybridwebview

xamarin.android
1个回答
0
投票

您可能想在C#中调用html JavaScript函数,如果可以,可以看一下:

有index.html,在PCL中添加,将Build Action设置为EmbeeddedResource,有一个函数,名为printMultiplicationTable

<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>

现在,您想用C#调用此JavaScript函数,

<StackLayout>
    <Label
        FontSize="Medium"
        HorizontalOptions="Center"
        Text="Multiplication Table" />
    <StackLayout HorizontalOptions="Center" Orientation="Horizontal">
        <Label Text="Number: " VerticalOptions="Center" />
        <Entry
            x:Name="numberEntry"
            Text="5"
            WidthRequest="40" />
        <Label Text="Stop:" VerticalOptions="Center" />
        <Entry
            x:Name="stopEntry"
            Text="10"
            WidthRequest="40" />
    </StackLayout>
    <Button
        x:Name="callJavaScriptButton"
        Clicked="OnCallJavaScriptButtonClicked"
        Text="Call JavaScript" />
    <WebView
        x:Name="webView"
        HorizontalOptions="FillAndExpand"
        VerticalOptions="FillAndExpand" />
</StackLayout>

 public MainPage()
    {
        InitializeComponent();
        webView.Source = LoadHTMLFileFromResource();
    }
    HtmlWebViewSource LoadHTMLFileFromResource()
    {
        var source = new HtmlWebViewSource();

        // Load the HTML file embedded as a resource in the PCL
        var assembly = typeof(MainPage).GetTypeInfo().Assembly;
        var stream = assembly.GetManifestResourceStream("CallJavaScript.index.html");
        using (var reader = new StreamReader(stream))
        {
            source.Html = reader.ReadToEnd();
        }
        return source;
    }

    private void OnCallJavaScriptButtonClicked(object sender, EventArgs e)
    {
        if (string.IsNullOrWhiteSpace(numberEntry.Text) || string.IsNullOrWhiteSpace(stopEntry.Text))
        {
            return;
        }

        int number = int.Parse(numberEntry.Text);
        int end = int.Parse(stopEntry.Text);

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

这是我的示例,您可以从github获得它:

https://github.com/CherryBu/CallJavaScript

更新:

enter image description here

再次更新:

如果要从C#调用html JavaScript函数,则可以在MainActivity.cs中配置Webview:

  WebSettings settings = webview1.Settings;
        settings.JavaScriptEnabled = true;
        // load the javascript interface method to call the foreground method
        //webview1.AddJavascriptInterface(new MyJSInterface(this), "CSharp");
        webview1.SetWebViewClient(new WebViewClient());        
        webview1.LoadUrl("file:///android_asset/login.html");

请在资产文件夹中添加html文件,并将BuildAction设置为AndroidAsset。

然后C#在JS中调用方法并获取回调值

class EvaluateBack : Java.Lang.Object, IValueCallback
{

    public void OnReceiveValue(Object value)
    {

        Toast.MakeText(Android.App.Application.Context,value.ToString(), ToastLength.Short).Show();// you will get the value "100"
    }


}

webview1.EvaluateJavascript("javascript: check();", new EvaluateBack());

这是github上的示例,您可以看一下:

https://github.com/CherryBu/CallJavaFunction

© www.soinside.com 2019 - 2024. All rights reserved.