8

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?

crowjonah
  • 2,858
  • 1
  • 23
  • 27
koalabruder
  • 2,794
  • 9
  • 33
  • 40

2 Answers2

6

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

koalabruder
  • 2,794
  • 9
  • 33
  • 40
  • 4
    Please post code rather than links. Also, the linked article is full of syntax errors and unclear. – Josh Noe Jul 22 '16 at 18:30
4

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>
mlemay
  • 1,622
  • 2
  • 32
  • 53
  • Does this work with WPF (System.Windows.Controls.WebBrowser)? I think you example works with Forms. – koalabruder Aug 21 '12 at 12:36
  • I don't know if it works with the WPF browser, in my code, I embedded the WinForm webbrowser in my WPF app, I'm gonna edit my answer with the code – mlemay Aug 21 '12 at 12:39