简体   繁体   中英

How to execute a Javascript function from a C# WebBrowser?

I'm doing some web automation via C# and a WebBrowser. There's a link which I need to 'click', but since it fires a Javascript function, apparently the code needs to be executed rather than just having the element clicked (ie element.InvokeMember("click")). Here's the href for the element, which opens an Ajax form:

javascript:__doPostBack("ctl00$cphMain$lnkNameserverUpdate", "")

I've tried:

webBrowser1.Document.InvokeScript("javascript:__doPostBack", new object[] { "ctl00$cphMain$lnkNameserverUpdate", "" });

and:

webBrowser1.Document.InvokeScript("__doPostBack", new object[] { "ctl00$cphMain$lnkNameserverUpdate", "" });

and a few other things. The code gets hit, but the script doesn't get fired. Any ideas would be most appreciated.

Gregg

BTW Here's the full element in case it's useful:

<a href="javascript:__doPostBack('ctl00$cphMain$lnkNameserverUpdate','')" onmouseout="window.status=''; return true" onmouseover="window.status='Update Nameservers'; return true" id="ctl00_cphMain_lnkNameserverUpdate" onclick="javascript:Layout.ChangeIframeToSrc('DropinLoad_Domain.aspx?controlRequest=ActionNameserversWithIP');return false;">NS51.DOMAINCONTROL.COM<br/>NS52.DOMAINCONTROL.COM<br/></a>
HtmlDocument doc = browser.Document;
HtmlElement head = doc.GetElementsByTagName("head")[0];
HtmlElement s = doc.CreateElement("script");
s.SetAttribute("text","function sayhello() { alert('hello'); }");
head.AppendChild(s);
browser.Document.InvokeScript("sayHello");

Have a look at this link:

http://msdn.microsoft.com/en-us/library/system.windows.forms.webbrowser.objectforscripting.aspx

I've actually used this in the past, and it works perfectly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM