65.9K
CodeProject is changing. Read more.
Home

Inject Scripts into a Page in WebBrowser Control

starIconstarIconstarIconstarIconstarIcon

5.00/5 (2 votes)

Mar 16, 2014

CPOL
viewsIcon

31584

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

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

C#

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

And a use example:

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:

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: