6

can I set a custom User Agent for a WebView?

I need to show mobile style of websites.

MBZ
  • 26,084
  • 47
  • 114
  • 191

3 Answers3

4

It's easy to do:

string ua = "Mozilla/5.0 (iPhone; CPU iPhone OS 6_0 like Mac OS X)" + "AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A5376e Safari/8536.25";
var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, new Uri(url));
httpRequestMessage.Headers.Add("User-Agent",ua);
webView1.NavigateWithHttpRequestMessage(hrm);
aloisdg
  • 22,270
  • 6
  • 85
  • 105
John TiXor
  • 73
  • 8
2

Per this MSDN Forum posting you cannot. Could you host a lightweight proxy service (say Azure Web Site) to proxy the request for you?

Jim O'Neil
  • 23,344
  • 7
  • 42
  • 67
  • Thanks Jim. Yeah, using a proxy is a solution of course. I was wondering if I can manage that without using one. – MBZ Dec 08 '12 at 19:00
2

You can load HTML with custom user agent and then pass the html to WebView

Loading html

var handler = new HttpClientHandler {AllowAutoRedirect = false};
var client = new HttpClient(handler);
client.DefaultRequestHeaders.Add("user-agent",
                                 "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; 
                                  WOW64; Trident/6.0)");
var response = await client.GetAsync(url);
response.EnsureSuccessStatusCode();
var html = await response.Content.ReadAsStringAsync();

assign html to WebView

WebView.NavigateToString(html);
Mayank
  • 8,777
  • 4
  • 35
  • 60
  • Thanks. This was the first thing that came to my mind, actually. But it became a serious pain. The user is not able to navigate or anything. And for some websites you will need to set much more than just User-Agent. – MBZ Dec 08 '12 at 19:00