Communication between WPF Windows App & HTML Page hosted in WebBrowser control

Datetime:2016-08-23 03:56:04          Topic: WPF  HTML           Share

Context

This can be considered as a continuation of one old post in this same blog. In that post we can see the technique to establish communication between HTML Page inside WebBrowser controls and and .Net application . In this post we are going to see the approach in detail. Code is available for download and is self explanatory.

Technical details

  • For WPF to JS communication
    • WebBrowser control has a method called InvokeScript.
    • This can be used to invoke any JavaScript function present in the rendered web page and pass parameters.
  • For Web page/JS to WPF .Net communication
    • WebBrowser has a property called ObjectForScripting which will be available in JS as window.external
    • If we set an object to ObjectForScripting property, that .Net object will be available in JS and from JS we can call any method on that object which will in turn call the .Net code.

What’s not done

This just proves the technique. Performance testing is not part of this.

Source code

  • The HTML page is inside the WPF.
  • WebBrowser loads the HTML page by usingpack: uri syntax.
  • WebBrowser's ObjectForScripting Object is set when the window loads
  • A class which is comvisible is used for the above property
  • From JavaScript the SetAValue() is called to pass data from JS to WPF
  • For WPF to JS myWebOC.InvokeScript() is invoked
  • In JS the data is received in the setSomeText() function.

Download from the below url.

https://www.dropbox.com/s/gcuzbgphk5a2nn9/WPF_HTML_Communication.zip?dl=0





About List