How to inject JavaScript in WebBrowser control?

JavascriptObject Oriented ProgrammingFront End Technology

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() {
      alert('Weclome')
   }";
   hElement.AppendChild(sElement);
   weBrowser.Document.InvokeScript("How you doing?");
}
raja
Published on 27-Feb-2018 17:22:10
Advertisements