I am using an MVVM pattern on WPF4, though I am new to both. I am looking for a good solution to using a WebBrowser control that can receive Javascript commands and communicate with the ViewModel. It needs the following:
- Ability to collect values from Javascript forms, and return them to the ViewModel
- Use Javascript to determine ReadyState before
- Running Javascript commands (setting form values, use form values for logical steps, submit form) some which happen across multiple page loads
The site being worked on is not under my control to edit or update. It makes heavy use of ActiveX and will not accept non-IE browsers (Awesomium will not work), so the standard WPF WebBrowser control is likely the only option.
This question provides a solution to binding the source of a browser control with an attached property. I think this could be adapted to use the navigate method to send javascript, though I am not sure how values could be returned to the Viewmodel. This is the major hurdle I need to get over.
Heavy Edit – Question receiving very low views and no answers, completely reworded
Well if you were working with the site developers to create a solution for your application, then you would use
ObjectForScriptingto communicate between JavaScript and the app. There a good article here, and another question which might be helpful here.However as I understand your question, the site is an arbitrary third party site with no affiliation to your application, and you want to auto-fill some form values and submit the form within your code.
To do this you can handle the
LoadCompletedevent of the WebBrowser. This is called when the loaded documentreadyStateis changed to completed. You can therefore use this event as a hook to then set/read the document form values. Note you will need to add a reference toMicrosoft mshtmlin the project.The following is an MVVM style (PRISM) command, which allows an event to bind directly to the
ViewModelusing behaviors. This is equivalent to registering an event handler in code-behind.Unfortunately the
NavigationEventArgsdon’t provide a way to access the HTML document or request data. It does contain aWebRequestproperty but this has not been implemented, and will always be null. In my example I’ve assumed a customEventToCommandWithSenderclass which providers the sender as well as the event ARGs when the event fires, but it’s down to your own implementation to get access to the sender.