如何使WebviewRenderer IOS外部URL访问?

时间:2019-05-02 13:47:21

标签: xamarin.forms

我做了一个IOS webviewrenderer,但是我无法访问像google这样的外部URL,我该怎么办?

我正在关注教程https://docs.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/custom-renderer/hybridwebview

public class HybridWebViewRenderer : ViewRenderer<HybridWebView, WKWebView>, IWKScriptMessageHandler
{
    const string JavaScriptFunction = "function invokeCSharpAction(data){window.webkit.messageHandlers.invokeAction.postMessage(data);}";
    WKUserContentController userController;

    protected override void OnElementChanged (ElementChangedEventArgs<HybridWebView> e)
    {
        base.OnElementChanged (e);

        if (Control == null) {
            userController = new WKUserContentController ();
            var script = new WKUserScript (new NSString (JavaScriptFunction), WKUserScriptInjectionTime.AtDocumentEnd, false);
            userController.AddUserScript (script);
            userController.AddScriptMessageHandler (this, "invokeAction");

            var config = new WKWebViewConfiguration { UserContentController = userController };
            var webView = new WKWebView (Frame, config);
            SetNativeControl (webView);
        }
        if (e.OldElement != null) {
            userController.RemoveAllUserScripts ();
            userController.RemoveScriptMessageHandler ("invokeAction");
            var hybridWebView = e.OldElement as HybridWebView;
            hybridWebView.Cleanup ();
        }
        if (e.NewElement != null) {
            var uri = e.NewElement.Uri.ToString();
            Control.LoadRequest(new NSUrlRequest(new NSUrl(uri, false)));
        }
    }

    public void DidReceiveScriptMessage (WKUserContentController userContentController, WKScriptMessage message)
    {
        Element.InvokeAction (message.Body.ToString ());
    }
}

1 个答案:

答案 0 :(得分:0)

与加载本地html文件不同。如果要访问google等远程URL,则无需设置参数isDir

if (e.NewElement != null) 
{
  var uri = e.NewElement.Uri.ToString();
  Control.LoadRequest(new NSUrlRequest(new NSUrl(uri)));
}