UWP WebViewでDOMとやり取りするにはどうすればよいですか?
あなたはHTMLのイベントハンドラを使用するためにJavaScriptのeval関数をInvokeScriptAsync
を使用することができ、かつWebView.ScriptNotify
を使用してアプリケーションに通知するHTMLイベントハンドラからwindow.external.notify使用します。
private async void Button_Click(object sender, RoutedEventArgs e)
{
string functionString = String.Format("document.getElementById('nameDiv').innerText = 'Hello, {0}';", nameTextBox.Text);
await webView1.InvokeScriptAsync("eval", new string[] { functionString });
}
ウェブビューのコンテンツのスクリプトでは、文字列パラメータを使用してwindow.external.notifyを使用して、アプリに情報を送り返すことができます。これらのメッセージを受け取るには、ScriptNotifyイベントを処理します。
public MyPage()
{
this.InitializeComponent();
MyWebView.ScriptNotify += MyWebView_ScriptNotify;
// Here we have to set the AllowedScriptNotifyUri property because we are
// navigating to some site where we don't own the content and we want to
// allow window.external.notify() to pass data back to the app.
List<Uri> allowedUris = new List<Uri>();
allowedUris.Add(new Uri("http://www.bing.com"));
MyWebView.AllowedScriptNotifyUris = allowedUris;
}
void MyWebView_ScriptNotify(object sender, NotifyEventArgs e)
{
// Respond to the script notification.
}
詳細については、UWP WebView
を参照してください。