Neir0
Neir0

Reputation: 13367

Set JavaScript events in WebBrowser control

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?

Upvotes: 1

Views: 1042

Answers (1)

Sheng Jiang 蒋晟
Sheng Jiang 蒋晟

Reputation: 15261

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.

Upvotes: 2

Related Questions