Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

In my WinForms application I need to call javascript function from my WebBrowser control. I used Document.InvokeScript and it works perfect with functions alone e.g

Document.InvokeScript("function").

But when i want to call javascript object method e.g.

Document.InvokeScript("obj.method")

it doesn't work. Is there a way to make it work? Or different solution to this problem? Without changing anything in the javascript code!

Thanks in advance :)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
603 views
Welcome To Ask or Share your Answers For Others

1 Answer

The example in the documentation does NOT include the parenthesis.

private void InvokeScript()
{
    if (webBrowser1.Document != null)
    {
        HtmlDocument doc = webBrowser1.Document;
        String str = doc.InvokeScript("test").ToString() ;
        Object jscriptObj = doc.InvokeScript("testJScriptObject");
        Object domOb = doc.InvokeScript("testElement");
    }
}

Try

Document.InvokeMethod("obj.method");

Note that you can pass arguments if you use HtmlDocument.InvokeScript Method (String, Object[]).

Edit

Looks like you aren't the only one with this issue: HtmlDocument.InvokeScript - Calling a method of an object . You can make a "Proxy function" like the poster of that link suggests. Basically you have a function that invokes your object's function. It's not an ideal solution, but it'll definitely work. I'll continue looking to see if this is possible.

Another post on same issue: Using WebBrowser.Document.InvokeScript() to mess around with foreign JavaScript . Interesting solution proposed by C. Gro? on CodeProject:

private string sendJS(string JScript) {
    object[] args = {JScript};
    return webBrowser1.Document.InvokeScript("eval",args).ToString();
}

You could make that an extension method on HtmlDocument and call that to run your function, only using this new function you WOULD include parenthesis, arguments, the whole nine yards in the string you pass in (since it is just passed along to an eval).

Looks like HtmlDocument does not have support for calling methods on existing objects. Only global functions. :(


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...