1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

WKWebViewでUserAgentにオリジナルの文字列を追加する

1
Posted at

Xamarin.FormsのWebView(WKWebView)でUserAgentを書き換えるのではなく、オリジナルの文字列を追加する

アプリ内のWebViewで開いた場合と、直接ブラウザで開いた場合の判定条件にオリジナルの文字列を使いたい場合。
WebViewのCustomUserAgentプロパティに文字列をセットすると本来のUserAgentが上書きされてしまうので、追加したい場合はまず自分自身のUserAgentを取得する必要がある。
そのために、WKWebViewのJavaScriptを実行するメソッド、EvaluateJavaScriptを使う。

WkWebViewRendererを継承したクラスを使う

MyWebViewRenderer.cs
[assembly:ExportRenderer(typeof(WebView), typeof(MyWebViewRenderer))]
namespace Sample.iOS
{
  public class MyWebViewRenderer : WKWebViewRenderer, IWKUIDelegate
  {
    this.EvaluateJavaScript("navigator.userAgent", (result, error) => 
    {
      if (result != null)
      {
        var agent = result.ToString();
        this.CustomUserAgent = agent + " MyApplication";
      }
    }
  }
// 以下省略
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?