How to inject JavaScript in WebBrowser control?

To inject JavaScript in WebBrowser control, use the following steps −

  •  Firstly, create a Windows Forms application in Visual Studio.
  •  Now, drag a WebBrowser control to the form
  •  Set the Url property.
  •  Right-click the project, choose to Add reference... → COM → Type Libraries
  •  Select "Microsoft HTML Object Library"

  Add the following code to inject JavaScript.

private void myWebBrowser(object sender, WebBrowserDocumentCompletedEventArgs e){
   // head element
   HtmlElement hElement = weBrowser.Document.GetElementsByTagName("head")[0];

   // script element
   HtmlElement sElement = weBrowser.Document.CreateElement("script");
   IHTMLScriptElement val = (IHTMLScriptElement)sElement.DomElement;

   element.text = "function sayHello() {
   weBrowser.Document.InvokeScript("How you doing?");