Detection of browser version in WPF
Is it possible to find out in what browser version a browser hosted application (XBAP) runs (eg. IE6, IE7 or IE8)? I want to find out the 开发者_运维技巧browser version from within the XBAP.
With some help from a Microsoft forum I was led into a direction that finally works. Below a proof of concept in C++.NET (.
using namespace System::Windows::Forms;
[STAThread]
String^ GetBrowserVersion() {
String^ strResult = String::Empty;
WebBrowser^ wb = gcnew WebBrowser();
String^ strJS = "<SCRIPT>function GetUserAgent() { return navigator.userAgent; }</SCRIPT>";
wb->DocumentStream = gcnew MemoryStream( ASCIIEncoding::UTF8->GetBytes(strJS) );
while ( wb->ReadyState != WebBrowserReadyState::Complete ) {
Application::DoEvents();
}
String^ strUserAgent = (String^)wb->Document->InvokeScript("GetUserAgent");
wb->DocumentStream->Close();
String^ strBrowserName = String::Empty;
int i = -1;
if ( ( i = strUserAgent->IndexOf( "MSIE" ) ) >= 0 ) {
strBrowserName = "Internet Explorer";
} else if ( ( i = strUserAgent->IndexOf( "Opera" ) ) >= 0 ) {
strBrowserName = "Opera";
} else if ( ( i = strUserAgent->IndexOf( "Chrome" ) ) >= 0 ) {
strBrowserName = "Chrome";
} else if ( ( i = strUserAgent->IndexOf( "FireFox" ) ) >= 0 ) {
strBrowserName = "FireFox";
}
if ( i >= 0 ) {
int iStart = i + 5;
int iLength = strUserAgent->IndexOf( ';', iStart ) - iStart;
strResult = strBrowserName + " " + strUserAgent->Substring( iStart, iLength );
}
return strResult;
}
I presume you mean Silverlight rather than WPF? (they're separate technologies, though similar).
Take a look at the System.Windows.Browser.BrowserInformation
Class
Specifically
System.Windows.Browser.BrowserInformation.BrowserVersion
From the MSDN page above:
using System;
using System.Windows.Controls; using System.Windows.Browser;
public class Example
{
public static void Demo(System.Windows.Controls.TextBlock outputBlock)
{
outputBlock.Text +=
"\nSilverlight can provide browser information:\n"
+ "\nBrowser Name = " + HtmlPage.BrowserInformation.Name
+ "\nBrowser Version = " +
HtmlPage.BrowserInformation.BrowserVersion.ToString()
+ "\nUserAgent = " + HtmlPage.BrowserInformation.UserAgent
+ "\nPlatform = " + HtmlPage.BrowserInformation.Platform
+ "\nCookiesEnabled = " +
HtmlPage.BrowserInformation.CookiesEnabled.ToString() + "\n";
}
}
int BrowserVer;
using (var wb = new System.Windows.Forms.WebBrowser())
{
BrowserVer = wb.Version.Major;
}
精彩评论