Forum Moderators: open

Message Too Old, No Replies

HtmlDocument.InvokeScript - Calling a method of an object

         

Fotiman

8:35 pm on Nov 11, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



According to the MSDN documentation, InvokeScript can be used to execute an Active Scripting function defined in an HTML page. So if my HTML contained this:


<script type="text/javascript">
function foo() {
alert('hello world');
}
</script>

Then I could access that in my C# application by doing:


webBrowser.Document.InvokeScript("foo");

(where webBrowser is an instance of WebBrowser)

However, if the page contains more complex script where I want to call a method of an object, I can't seem to figure out how to do that. For example:


<script type="text/javascript">
var myObj = {
foo: function () {
alert('hello world');
}
};
</script>

In other words, I want to call myObj.foo(), but if I call InvokeScript("myObj.foo"), it doesn't work. Does anyone know of any ways to do this?

Fotiman

3:47 pm on Nov 12, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Note, I was able to "hack" around this, but I'd still like to know if there is a better solution.

My hack was to create a single public method which just acts as a sort of proxy to my real object:


function proxy(s1,s2,s3,s4,s5,s6,s7,s8,s9) {
var args = Array.prototype.slice.call(arguments);
var fn = args.shift();
return myObj[fn].apply(myObj,args);
}

This, of course, means all of my calls to InvokeScript need to pass the real method as an argument:


webBrowser.Document.InvokeScript("proxy", new object[] {"foo"});
webBrowser.Document.InvokeScript("proxy", new object[] {"bar", "arg1", "arg2"});

The problem with this is that it's not as clear that the first argument is really a function name. It just feels messy to me. Anyone have a better alternative?