ios - 在 UIWebview iOS 中从 javascript 调用 C# 方法的最简单方法是什么?

标签 ios xamarin

我正在使用 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)。

最佳答案

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

1) 在您的网络代码中初始化网站导航,例如

http://scancode/providedBarCode

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

Xamarin Forms(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(ShouldStartLoad UIWebView 的方法)

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/

相关文章:

mvvm - 嵌套 View 模型的嵌套 View

ios - 了解handleWatchKitExtensionRequest

c# - 无法从xamarin android调用firebase云函数

ios - NSUserDefaults和原始数据类型?

ios - 有没有一种有效的方法来创建大量 GMSMarker 对象?

c# - 为什么要更改后退按钮的标题?

c# - 垃圾收集器无法为主要堆部分分配 16384 字节的内存

ios - Xamarin.iOS 中未加载设置包中的默认值

ios - UITableView Cell 不应水平快速滚动 iOS

android - 我应该如何着手制作一个简单的移动应用程序?钛还是原生?