Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / Javascript

Inject Scripts into a Page in WebBrowser Control

5.00/5 (2 votes)
15 Mar 2014CPOL 31.6K  
Inject a script (JavaScript) into a web page loaded in a WebBrowser control.

Introduction

In this tip, I will show the easiest way to inject a script (JavaScript) into a web page loaded in a WebBrowser control.

Background

Basically, what this code does is invoke the global JavaScript eval() function, passing as parameter the script you want to invoke.

The eval() function evaluates or executes an argument. If the argument is an expression, eval() evaluates the expression. If the argument is one or more JavaScript statements, eval() executes the statements.

Using the Code

Below, you can see an implementation of a method for injecting scripts:

VB.NET

VB.NET
Public Sub InjectScript(Script As String)
    WebBrowser1.Document.InvokeScript("eval", New Object() {Script})
End Sub  

C#

C#
public void InjectScript(string Script)
{    
    WebBrowser1.Document.InvokeScript("eval", new object[] { Script });
}  

And a use example:

C#
System.Text.StringBuilder scriptBuilder = new System.Text.StringBuilder();

scriptBuilder.AppendLine("{");
scriptBuilder.AppendLine("var text = ""JavaScript injection test"";");
scriptBuilder.AppendLine("alert(text);");
scriptBuilder.Append("}");
            
string script = scriptBuilder.ToString();
            
InjectScript(script); 

Remarks

If the script passed as parameter in InvokeScript returns a value, this value will be returned by InvokeScript, because it's a function!

So, you can do something like this:

C#
string script = "function() { return document.getElementById('Example').innerText; }"; 
string elementInnerText = (string)WebBrowser1.Document.InvokeScript("eval", new object[] { script });

PS.: The code above is just to illustrate the concept. I did not test.

Original Source

This was originally posted on my personal blog (in Brazilian Portuguese). However, I thought it would be interesting to write a post about it in English.

However, if you speak Portuguese, feel the urge to visit the original article:

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)