问题
Is there any mechanism that I can push data into a webbrowser control from the containing windows forms application. Specifically the webbrowser control contains some knockout.js and I want to allow some external events such as changes to certain files in the local filesystem to update the knockout viewModel.
At the moment I have this working after a fashion with the JS in the webbrowser control issuing a longpolling jsonp requests to a micro webserver I have written running in the windows forms application (note that this is not the place that the web page itself is server from hence jsonp. Also, the micro webserver is basically just a httpListner). When the forms app receives a file change event it returns a response via the micro webserver and that updates the knockout viewmodel.
The problem is this all feels fragile - if the file events come thick and fast they can start being skipped - it looks like my micro webserver is trying to return multiple results to the same stream. I can fix that, but overall its looking nasty and fragile.
The question is: am I missing any much simpler way to have the containing application signal something (i.e. pass some JSON) to the web page running in a webbrowsercontrol (without a page refresh!)
回答1:
You could create an element, say a div with an id
<div id='external-json' data-bind='jsonHandler : {}' style='display:none'></div>
Then write json to this div from within your winforms app..
var myJson = "{test : 1}";
this.browser.Document.Body.GetElementById("external-json").innerText = myJson;
You could even create a knockout custom binding to react to this
ko.bindingHandlers.jsonHandler = {
update: function(element, valueAccessor) {
//do something with the json
var json = element.innerText;
var obj = eval(json); //hmm
alert(obj.test);
}
};
This is obviously a simple example and you could probably improve the idea a lot, you may need a queue of messages, possibly calling a function in your client script instead of using the element.
来源:https://stackoverflow.com/questions/8445302/how-can-i-communicate-between-a-windows-forms-application-and-a-webbrowser-contr