獲取 Windows Phone 的 User-Agent 字串

l_serein發表於2013-01-29

[程式碼] 使用方法

01 public partial class HomeView : PhoneApplicationPage
02 {
03     public HomeView()
04     {
05         InitializeComponent();
06         Loaded += HomeView_Loaded;
07     }
08   
09     private void HomeView_Loaded(object sender, RoutedEventArgs e)
10     {
11         UserAgentHelper.GetUserAgent(
12             LayoutRoot,
13             userAgent =>
14                 {
15                     // TODO: Store this wherever you want
16                     ApplicationSettings.Current.UserAgent = userAgent;
17                 });
18     }
19 }

[程式碼] 工具類

01 public static class UserAgentHelper
02 {
03     private const string Html =
04         @"<!DOCTYPE HTML PUBLIC ""-//W3C//DTD HTML 4.01 Transitional//EN"">
05   
06         <html>
07         <head>
08         <script language=""javascript"" type=""text/javascript"">
09             function notifyUA() {
10                window.external.notify(navigator.userAgent);
11             }
12         </script>
13         </head>
14         <body onload=""notifyUA();""></body>
15         </html>";
16   
17     public static void GetUserAgent(Panel rootElement, Action<string> callback)
18     {
19         var browser = new Microsoft.Phone.Controls.WebBrowser();
20         browser.IsScriptEnabled = true;
21         browser.Visibility = Visibility.Collapsed;
22         browser.Loaded += (sender, args) => browser.NavigateToString(Html);
23         browser.ScriptNotify += (sender, args) =>
24                                     {
25                                         string userAgent = args.Value;
26                                         rootElement.Children.Remove(browser);
27                                         callback(userAgent);
28                                     };
29         rootElement.Children.Add(browser);
30     }
31 }

相關文章