How to communicate between WPF and JavaScript in a WebBrowser instance?

帅比萌擦擦* 提交于 2019-12-10 03:47:12

问题


I have a C#/WPF application with an embedded browser (WebBrowser) with some JavaScript. How can they communicate with each other in both directions? Is it practicable to use the URL?

JS->WPF: Listen for changes. WPF->JS: Change the URL to javascript:alert('hello');

Is there a better way?


回答1:


It's important to know that there are two WebBrowser. One for Windows Forms and one for WPF. The link below uses the WPF one. http://www.dotnetfunda.com/articles/article840-working-with-webbrowser-in-wpf.aspx




回答2:


To invoke JavaScript function from C#

object result = mWebBrowser.Document.InvokeScript("FunctionName", new String[] { Parameter1 });

// If the function succeed (my function return a boolean)
if (null == result || result.ToString().ToLower() == "false")
{
   // Code
}

Is this what you want? Like this your c# code call your javascript, and it returns a value

My WPF Xaml:

<UserControl x:Class="MediaViewer.WebViewer"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:wf="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms">
   <WindowsFormsHost>
      <wf:WebBrowser x:Name="mWebBrowser" />
   </WindowsFormsHost>
</UserControl>


来源:https://stackoverflow.com/questions/12052992/how-to-communicate-between-wpf-and-javascript-in-a-webbrowser-instance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!