简体   繁体   English

如何在Xamarin.Forms iOS应用程序中为UiWebView设置用户代理

[英]How to set user agent for UiWebView in Xamarin.Forms iOS app

I am currently setting the user agent of the UIWebView within my HybridWebViewRenderer in my iOS project in my Xamarin.Forms app. 我目前正在我的Xamarin.Forms应用程序中的iOS项目中的HybridWebViewRenderer中设置UIWebView的用户代理。

It does work but only at first, subsequent web requests do not have the UserAgent. 它确实有效,但仅在开始时,后续Web请求没有UserAgent。

I am setting the UserAgent as follows in OnElementChanged in HybridWebViewRenderer and my understanding is that this will be called once when the WebView is created. 我在HybridWebViewRenderer中的OnElementChanged中按如下方式设置UserAgent,我的理解是在创建WebView时将调用一次。

   public class HybridWebViewRenderer : ViewRenderer<HybridWebView, UIWebView>, IWKScriptMessageHandler
{
    protected override void OnElementChanged(ElementChangedEventArgs<HybridWebView> e)
    {
        base.OnElementChanged(e);

        if (Control == null)
        {
            UIWebView agentWebView = new UIWebView();
            var userAgent = agentWebView.EvaluateJavascript("navigator.userAgent");
            userAgent += "MyApp";
            NSDictionary dictionary = NSDictionary.FromObjectAndKey(NSObject.FromObject(userAgent), NSObject.FromObject("UserAgent"));
            NSUserDefaults.StandardUserDefaults.RegisterDefaults(dictionary);
            agentWebView.ShouldStartLoad += HandleStartLoad;
            base.SetNativeControl(agentWebView);
            agentWebView.LoadRequest(new NSUrlRequest(new NSUrl(e.NewElement.Uri.ToString())));

        }
    }

我使用完全相同的代码,但我在构造函数而不是OnElementChanged事件中执行此操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM