如何在 Xamarin 中将 WebView 移动设备设置为桌面模式

huangapple go评论66阅读模式
英文:

How to set webview mobile to desktop mode using Xamarin

问题

以下是代码的中文翻译部分:

public partial class MainPage : ContentPage
{
    public MainPage()
    {
        InitializeComponent();
        webView.Source = "https://www.example.com/";
        webView.Navigating += WebView_Navigating;
    }

    private void WebView_Navigating(object sender, WebNavigatingEventArgs e)
    {
        // 将User-Agent字符串设置为桌面浏览器的用户代理
        webView.Eval("navigator.userAgent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'");
    }
}

希望这个翻译对你有所帮助。如果你有任何其他问题,请随时提出。

英文:

Tried this

public partial class MainPage : ContentPage
{
    public MainPage()
    {
        InitializeComponent();
        webView.Source = "https://www.example.com/";
        webView.Navigating += WebView_Navigating;
    }

    private void WebView_Navigating(object sender, WebNavigatingEventArgs e)
    {
        // Set the User-Agent string to a desktop browser user agent
        webView.Eval("navigator.userAgent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'");
    }
}

please help in changing to desktop mode using Xamarin

答案1

得分: 1

在Android中,您需要实现一个自定义渲染器。

在Android文件夹中创建一个自定义渲染器(DesktopWebViewRenderer.cs):

[assembly: ExportRenderer(typeof(WebView), typeof(DesktopWebViewRenderer))]
namespace forms.Droid
{
    public class DesktopWebViewRenderer : WebViewRenderer
    {
        public DesktopWebViewRenderer(Context context) : base(context)
        {
        }

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

            Control.Settings.UserAgentString
                = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36";

        }
    }
}
英文:

In Android you have to implement a custom renderer.

Create a Custom Renderer(DesktopWebViewRenderer.cs) in Android folder:

[assembly: ExportRenderer(typeof(WebView), typeof(DesktopWebViewRenderer))]
namespace forms.Droid
{
    public class DesktopWebViewRenderer : WebViewRenderer
    {
        public DesktopWebViewRenderer(Context context): base(context)
        {
        }

        protected override void OnElementChanged(ElementChangedEventArgs&lt;WebView&gt; e)
        {
            base.OnElementChanged(e);

            Control.Settings.UserAgentString
                = &quot;Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36&quot;;

        }
    }
}

huangapple
  • 本文由 发表于 2023年2月19日 19:49:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/75499925.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定