views:

47

answers:

1

Hi

I have a WebBrowser control and try to set onclick and href attributes on all links.

foreach (HtmlElement link in webBrowser1.Document.Links)
{
      link.SetAttribute("href", "http://www.google.com");
      link.SetAttribute("onclick", "return false;");
}

It works well. When i out source code of outer html i see that attributes was exist. But JavaScript code does not work. Why and how i can force WebBrowser control to execute javascript code?

+1  A: 

onclick is a property of type IDispatch. You can assign a function with no parameter to the property or add an attribute to HTML and let the parser to do this for you but you can't assign a string to it via DOM.

You can either pass an object that implements IDispatch and the default method (dispid=0) to the property, or use IHTMLElement2::attachEvent to attach an event handler. If you are using Microsoft's class libraries, you can use Microsoft's wrappers like HtmlElement.AttachEventHandler in Windows Forms and HtmlElement.Attachevent in Silverlight.

Sheng Jiang 蒋晟