As you know, we can recover the UserAgent from web browser using javascript, specifically using the navigator object. With this object we can see the platform version, user agent and other properties of our browser, in this case we will use the navigator.userAgent property.
Windows Phone do not allow us exec javascript in native mode, but we can do this inside a WebBrowser control, for this, you can follow these setps:
1) Add a WebBrowser control to our PhoneApplication page.
2) Using the function NavigateToString to load the script, you can see the script in the example showed below.
3) Finally we intercept the ScriptNotify event from WebBowser control and we will process and store the value in the IsolatedStorage for when we need.
Declare a WebBroser control.
private WebBrowser webBrowserControl;
In the constructor of our PhoneApplicationPage, instance and add the control.
public ManiPage()
{
(…)
control.Loaded += new RoutedEventHandler(webBrowserControl_Loaded);
webBrowserControl = new WebBrowser();
webBrowserControl.IsScriptEnabled = true;
webBrowserControl.Visibility = System.Windows.Visibility.Collapsed;
webBrowserControl.ScriptNotify += new EventHandler<NotifyEventArgs>(webBrowserControl_ScriptNotify);
contentPanel.Children.Add(webBrowserControl);
}
When the WebBrowser control is loaded completely, we will load the scritp using NavigateToString function.
void webBrowserControl_Loaded(object sender, RoutedEventArgs e)
{
string html = @"<!DOCTYPE HTML PUBLIC ""-//W3C//DTD HTML 4.01 Transitional//EN"">
<html>
<head>
<script language=""JavaScript"" type=""text/JavaScript"">
function getUserAgent() {
window.external.notify(navigator.userAgent);
}
</script>
</head>
<body onload=""getUserAgent();""></body>
</html>";
webBrowserControl.NavigateToString(html);
}
Finally process the ScriptNotifi event and recover the UserAgent value. The format of UserAgent looks like this (in this case the User Agent of a Windows Phone Emulator)
Mozilla/4.0 (compatible; MSIE 7.0; Windows Phone OS 7.0; Trident/3.1; IEMobile/7.0; Microsoft; XDeviceEmulator)
void webBrowserControl_ScriptNotify(object sender, NotifyEventArgs e)
{
_userAgent = e.Value;
System.IO.IsolatedStorage.IsolatedStorageSettings.ApplicationSettings["UserAgent"] = _userAgent;
if (UserAgentChanged != null)
{
UserAgentChanged(e.Value, new EventArgs());
}
}
NOTE: If you want to recover this value later, you can do this:
string userAgent;
System.IO.IsolatedStorage.IsolatedStorageSettings.ApplicationSettings.TryGetValue<string>("UserAgent", out userAgent);
No comments:
Post a Comment