Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to inject JavaScript in WebBrowser control?
To inject JavaScript in WebBrowser control, you need to create a Windows Forms application and use the WebBrowser control's document manipulation capabilities. This allows you to dynamically add JavaScript code to web pages loaded in your application.
Prerequisites
- Create a Windows Forms application in Visual Studio
- Drag a WebBrowser control to the form
- Set the Url property of the WebBrowser control
- Right-click the project, choose Add reference... ? COM ? Type Libraries
- Select "Microsoft HTML Object Library"
Method 1: Injecting Script via DOM Manipulation
This approach creates a script element and appends it to the document head:
private void InjectJavaScript(object sender, WebBrowserDocumentCompletedEventArgs e)
{
// Get the head element
HtmlElement headElement = webBrowser.Document.GetElementsByTagName("head")[0];
// Create script element
HtmlElement scriptElement = webBrowser.Document.CreateElement("script");
IHTMLScriptElement scriptObj = (IHTMLScriptElement)scriptElement.DomElement;
// Set JavaScript code
scriptObj.text = @"
function sayHello() {
alert('Welcome to our application!');
}
function changeBackgroundColor() {
document.body.style.backgroundColor = 'lightblue';
}
";
// Append to head
headElement.AppendChild(scriptElement);
// Execute the injected function
webBrowser.Document.InvokeScript("sayHello");
}
Method 2: Direct Script Execution
You can also execute JavaScript directly without creating DOM elements:
private void ExecuteJavaScript()
{
string jsCode = @"
var newDiv = document.createElement('div');
newDiv.innerHTML = 'This content was added by injected JavaScript!';
newDiv.style.color = 'red';
newDiv.style.fontSize = '18px';
document.body.appendChild(newDiv);
";
webBrowser.Document.InvokeScript("eval", new object[] { jsCode });
}
Complete Example
Here's a complete working example showing how to inject and execute JavaScript:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
webBrowser1.DocumentCompleted += WebBrowser_DocumentCompleted;
webBrowser1.Navigate("https://www.example.com");
}
private void WebBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
// Ensure document is fully loaded
if (e.Url.AbsolutePath != webBrowser1.Url.AbsolutePath)
return;
InjectCustomScript();
}
private void InjectCustomScript()
{
try
{
HtmlElement head = webBrowser1.Document.GetElementsByTagName("head")[0];
HtmlElement scriptEl = webBrowser1.Document.CreateElement("script");
IHTMLScriptElement element = (IHTMLScriptElement)scriptEl.DomElement;
element.text = @"
function customAlert(message) {
alert('Custom Function: ' + message);
}
function highlightLinks() {
var links = document.getElementsByTagName('a');
for(var i = 0; i < links.length; i++) {
links[i].style.backgroundColor = 'yellow';
}
}
";
head.AppendChild(scriptEl);
// Execute the injected functions
webBrowser1.Document.InvokeScript("customAlert", new object[] { "JavaScript injected successfully!" });
webBrowser1.Document.InvokeScript("highlightLinks");
}
catch (Exception ex)
{
MessageBox.Show("Error injecting JavaScript: " + ex.Message);
}
}
}
Key Points
- Use the
DocumentCompletedevent to ensure the page is fully loaded before injecting scripts - Always wrap JavaScript injection in try-catch blocks for error handling
- The
IHTMLScriptElementinterface requires adding a reference to Microsoft HTML Object Library - Use
InvokeScript()to execute JavaScript functions after injection - Check the URL in DocumentCompleted to avoid multiple injections during navigation
Conclusion
JavaScript injection in WebBrowser control enables dynamic web page manipulation in Windows Forms applications. Use DOM manipulation for persistent scripts or direct execution for immediate actions, always ensuring proper error handling.
