How to get actual JavaScript value in onclick from webbrowser control?

≡放荡痞女 提交于 2019-11-30 05:01:53

There are number of ways you can do it.

  1. There is an Event object in DOM, which will give you information about which element generated this event.
  2. You can look at here, http://msdn.microsoft.com/en-us/library/ff975965%28v=VS.85%29.aspx
  3. This one is good, you can use this easily, you will get the event object as method parameter which you can investigate parameters to find out the source of the event. http://support.microsoft.com/kb/312777

Another alternative is to use a custom navigation url and act upon it

  1. Override BeforeNavigate event
  2. Check for Navigation url if it contains "mycommand:click" or "mycommand:clickandwait" 3. If it contains any of this, then set cancel as true. (this will stop navigation by browser).
  3. Then you can navigate your webbrowser code from your C# code and pass cancel as true.

Another Alternative method is to use External object, WebBrowser allows you to set an ObjectForScripting which you can access within Javascript of HTML.

ObjectForScripting in .NET 2.0

[ComVisible(true)]
public class MyClass
{
   // can be called from JavaScript
   public void ShowMessageBox(string msg){
       MessageBox.Show(msg);
   }
}

myBrowser.ObjectForScripting = new MyClass(); 
// or you can reuse instance of MyClass

And you can call,

window.external.ShowMessageBox("This was called from JavaScript");

Cast the element object to mshtml.IHTMLDOMNode, then read the attributes via IHTMLDOMNode.attributes. HtmlElement.GetAttribute is getting the IDispatch interface of the jscript function generated from the embedded attribute.

You can try to parse webBrowser1.DocumentText property using HtmlAgilityPack and then get desired result using XPath.

Dennis Röttger

If you don't HAVE to do it with C# (you can do it with JS and create a Postback) you should take a look at THIS question.

As per Sheng Jiang's response, here is some working sample:

IHTMLElement element = YourCodeToGetElement();
string onclick = string.Empty;

IHTMLDOMNode domNode = element as IHTMLDOMNode;
IHTMLAttributeCollection attrs = domNode.attributes;

foreach (IHTMLDOMAttribute attr in attrs)
{
    if (attr.nodeName.Equals("onclick"))
    {
        string attrValue = attr.nodeValue as string;
        if (!string.IsNullOrEmpty(attrValue))
        {
            onclick = attr.nodeValue;
            break;
        }
    }
}

You can parse it yourself easily, by first reading obj.outerHtml. That should give you the entire html for that obj, then search it for the value onclick="????" and extract the ???? part.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!