Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
615 views
in Technique[技术] by (71.8m points)

c# - Calling javascript object method using WebBrowser.Document.InvokeScript

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

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

1 Reply

0 votes
by (71.8m points)

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. :(


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...