Skip to content

Instantly share code, notes, and snippets.

@adriankeenan
Last active December 25, 2015 23:08
Show Gist options
  • Save adriankeenan/7054544 to your computer and use it in GitHub Desktop.
Save adriankeenan/7054544 to your computer and use it in GitHub Desktop.
Helper async class for getting the user agent string on Windows Phone

UserAgentHelper.cs

This class will allow you to attain the real user agent string for a device, as used by the embedded WebBrowser control.

A meaningful user agent string can then be manually set for HTTP requests instead of the default NativeHost user agent that is sent by the WebClient.

An example user agent would look something like: Mozilla/5.0 (compatible; MSIE 9.0; Windows Phone OS 7.5; Trident/5.0; IEMobile/9.0; NOKIA; Lumia 920)

Usage

  1. Create an instance of the helper
  2. Create a handler for GotUserAgent
  3. Grab the user agent string from UserAgentEventArgs

After attaining the user agent with this class you can attach it to WebClient request as follows:

WebHeaderCollection headers = new WebHeaderCollection();
headers[HttpRequestHeader.UserAgent] = userAgentString;

WebClient webClient = new WebClient();
webClient.Headers = headers;

Limitations

When targeting your application at Windows Phone 7.1, the user agent will always state Windows Phone OS 7.5 even on 8.0 and above.

class UserAgentHelper
{
private WebBrowser uaBrowser;
public event EventHandler<UserAgentEventArgs> GotUserAgent;
private const string html =
@"<html>
<head>
<script language=""javascript"" type=""text/javascript""></script>
</head>
</html>";
public UserAgentHelper()
{
uaBrowser = new WebBrowser();
uaBrowser.IsScriptEnabled = true;
uaBrowser.NavigateToString(html);
uaBrowser.Navigated += (webBrowserSender, args) =>
{
WebBrowser wb = webBrowserSender as WebBrowser;
String ua = (string)wb.InvokeScript("eval", "navigator.userAgent");
GotUserAgent(null, new UserAgentEventArgs() { userAgentString = ua });
};
}
}
public class UserAgentEventArgs : EventArgs
{
public string userAgentString { get; set; }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment