WKWebView.EvaluateJavaScript 从不返回

问题描述:

我正在尝试使用 WKWebView.EvaluateJavaScript(string, WKJavascriptEvaluationResult) 从我的 javascript 代码获取一个值返回到我的应用程序.问题是,委托 WKJavascriptEvaluationResult 从未被调用.这是我的代码:

I'm trying to get a value from my javascript code back to my application using WKWebView.EvaluateJavaScript(string, WKJavascriptEvaluationResult). The problem is, the delegate WKJavascriptEvaluationResult is never called. Here's my code:

C#:

TaskCompletionSource<NSObject> tcs = new TaskCompletionSource<NSObject>();

webView.EvaluateJavaScript(javascript, (result, error) =>
    {
        tcs.SetResult(result);
    });

return tcs.Task.Result;

Javascript:

Javascript:

function a()
{
    return "test";
}

a();

应用程序停留在 Wait() 调用上并且永远不会返回,因为 WKJavascriptEvaluationResult 永远不会被调用.是否有我不知道的已知问题?有没有更好的方法可以将我的 javascript 代码中的值获取到我的应用程序中,还是我没有正确使用它?

The application is stuck on the Wait() call and never returns because the WKJavascriptEvaluationResult never gets called. Is there a know issue that I'm not aware of? Is there a better way to get values from my javascript code to my application, or am I not using it correctly?

注意:我使用 TaskCompletionSource 只是为了使整个方法同步.

Note: I'm using a TaskCompletionSource simply to make the whole method synchronous.

如果您使用 Xamarin IOS,在 Xamarin Forms 中为我工作应该是相同的.

Worked for me in Xamarin Forms should be the same if you are using Xamarin IOS.

    public class IosWebViewRenderer : ViewRenderer<HybridWebView, WKWebView>
    {
        const string HtmlCode = "document.body.outerHTML";

        protected override void OnElementChanged(ElementChangedEventArgs<HybridWebView> e)
        {
            base.OnElementChanged(e);
            if (Control == null)
            {
                WKWebView wKWebView = new WKWebView(Frame, new WKWebViewConfiguration());
                wKWebView.NavigationDelegate = new WebViewDelate();
                SetNativeControl(wKWebView);
            }
            if (e.NewElement != null)
            {
                NSUrlRequest nSUrlRequest = new NSUrlRequest(new NSUrl(hybridWebView.Uri.ToString()));
                Control.LoadRequest(nSUrlRequest);
            }
        }

        class WebViewDelate : WKNavigationDelegate
        {
            public override void DidFinishNavigation(WKWebView webView, WKNavigation navigation)
            {
                WKJavascriptEvaluationResult handler = (NSObject result, NSError error) => {
                    if (error != null)
                    {
                        Console.WriteLine(result.ToString());
                    }
                };
                webView.EvaluateJavaScript(HtmlCode, handler);
            }
        }
    }