Welcome to WebmasterWorld Guest from 35.171.45.91

Forum Moderators: ocean10000

Message Too Old, No Replies

HtmlDocument.InvokeScript - Calling a method of an object

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

Senior Member from US 

WebmasterWorld Senior Member fotiman is a WebmasterWorld Top Contributor of All Time 10+ Year Member Top Contributors Of The Month

joined:Oct 17, 2005
posts: 5021
votes: 26


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?

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

Senior Member from US 

WebmasterWorld Senior Member fotiman is a WebmasterWorld Top Contributor of All Time 10+ Year Member Top Contributors Of The Month

joined:Oct 17, 2005
posts:5021
votes: 26


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?