WebBrowserコントロールは、Silverlightアプリケーション側からJavaScriptを実行することが出来ます。
前準備
XAMLの実装
WebBrowserコントロールを一つだけ設置しています。名前を「webBrowser」にしています。WebBrowserコントロールでJavaScriptを使用する場合は、IsScriptEnabledプロパティにTrueを設定しておいてください。
<phone:PhoneApplicationPage x:Class="WebBrowserJavaScriptTest.MainPage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone" xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="768" FontFamily="{StaticResource PhoneFontFamilyNormal}" FontSize="{StaticResource PhoneFontSizeNormal}" Foreground="{StaticResource PhoneForegroundBrush}" SupportedOrientations="Portrait" Orientation="Portrait" shell:SystemTray.IsVisible="True"> <Grid x:Name="LayoutRoot" Background="Transparent"> <Grid x:Name="ContentPanel" Grid.Row="0"> <phone:WebBrowser Name="webBrowser" IsScriptEnabled="True" /> </Grid> </Grid> </phone:PhoneApplicationPage>
JavaScriptを使ってWebBrowserコントロールを制御する
WebBrowserコントロールで表示しているページのタイトルを取得する
HTMLのtitleタグの値(ページのタイトル)を取得したい任意のタイミングで、WebBrowser.InvokeScriptメソッドを使って以下のJavaScriptを実行します。
// WebBrowserコントロールで表示しているタイトルを取得する var title = webBrowser.InvokeScript("eval", "document.title");
WebBrowserコントロールで表示しているページのURLを取得する
// WebBrowserコントロールで表示しているURLを取得する var strURL = webBrowser.InvokeScript("eval", "document.URL");
WebBrowserコントロールで表示しているテキストボックスの値を取得する
以下のようなテキストボックス(パスワード入力欄)を持つHTMLがあります。
<input id="password" type="password" />
このパスワード入力欄は「password」というIDを持っています。IDから要素を取得するには、JavaScriptのdocument.getElementByIdメソッドを使います。取得した要素のvalueプロパティを取得することで、現在何が入力されているのかを知ることが出来ます。
// WebBrowserコントロールで表示しているテキストボックスの値を取得する var value = webBrowser.InvokeScript("eval", "document.getElementById('password').value");
WebBrowserコントロールで表示しているテキストボックスに値を設定する(戻り値は設定した値)
以下のようなテキストボックス(パスワード入力欄)を持つHTMLがあります。
<input id="password" type="password" />
このパスワード入力欄は「password」というIDを持っています。IDから要素を取得するには、JavaScriptのdocument.getElementByIdメソッドを使います。取得した要素のvalueプロパティに値を設定することが出来ます。
// WebBrowserコントロールで表示している // テキストボックスに値を設定する(戻り値は設定した値) var hoge = webBrowser.InvokeScript("eval", "document.getElementById('password').value = 'hogehgoe'");
上記のコードを任意のタイミングで実行すると、hogehogeがテキストボックスに反映されます。