简体   繁体   English

如何从C#WebBrowser执行Javascript函数?

[英]How to execute a Javascript function from a C# WebBrowser?

I'm doing some web automation via C# and a WebBrowser. 我正在通过C#和WebBrowser进行一些Web自动化。 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")). 我需要单击一个链接,但是由于它会触发Javascript函数,因此显然需要执行代码,而不仅仅是单击元素(即element.InvokeMember(“ click”))。 Here's the href for the element, which opens an Ajax form: 这是元素的href,它将打开一个Ajax表单:

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 http://msdn.microsoft.com/zh-CN/library/system.windows.forms.webbrowser.objectforscripting.aspx

I've actually used this in the past, and it works perfectly. 实际上,我过去曾经使用过它,并且效果很好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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