OGeek|极客世界-中国程序员成长平台

标题: ios - 在 UIWebview iOS 中从 javascript 调用 c# 方法的最简单方法是什么? [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 15:56
标题: ios - 在 UIWebview iOS 中从 javascript 调用 c# 方法的最简单方法是什么?

我正在使用 Xamarin 开发 iOS 应用程序。我有一个 从 UIWebView 中的 JavaScript 调用 c# 方法的要求。我们怎样才能做到这一点?

以下是正在加载到 UIWebView 中的 html 内容

const string html = @"
                    <html>
                      <body onload=""setBarcodeInTextField()"">
                        <p>Demo calling C# from JavaScript</p>
                        <button type=""button"" 
                                onClick=""CSharp.ScanBarcode('txtBarcode', 'setBarcodeInTextField')"">Scan Barcode
                        </button>
                        <input type=""text"" value="""" id=""txtBarcode""/>

                        <script type=""text/javascript"">



                        function setBarcodeInTextField() {

                            alert(""JS"");
                        }

                        </script>

                      </body>
                    </html>"; 

另外,当 UIWebView 加载 html 内容时,我在警报消息中收到 about://(null)(在 body 标记上指定用于显示警报的 onload)。



Best Answer-推荐答案


从 WebView 组件中显示的网站触发 C# 方法的一种解决方案是:

1) 在你的网页代码中初始化一个网站导航,例如

http://scancode/providedBarCode

2) 然后您可以覆盖在导航实际发生之前调用的 webview 方法。您可以在那里拦截带有参数的调用并忽略实际导航

Xamarin 表单(Navigating WebView 方法)

webview.Navigating += (s, e) =>
{
    if (e.Url.StartsWith("http://scancode/"))
    {
        var parameter = e.Url.Split(new[] { "scancode/" }, StringSplitOptions.None)[1];
        // parameter will be providedBarCode

        // perform your logic here

        // cancel the actual navigation
        e.Cancel = true;
    }
};

Xamarin iOS(UIWebView 的 ShouldStartLoad 方法)

webViewControl.ShouldStartLoad = (webView, request, navType) =>
{
    var path = request.Url.AbsoluteString;
    if (path.StartsWith("http://scancode/"))
    {
        var parameter = path.Split(new[] { "scancode/" }, StringSplitOptions.None)[1];
        // parameter will be providedBarCode

        // perform your logic here

        // cancel the actual navigation
        return false;
    }

    return true;
}

关于ios - 在 UIWebview iOS 中从 javascript 调用 c# 方法的最简单方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49732217/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4