Ability to execute JavaScript code on the loaded web page is one of the main features of DotNetBrowser. To execute JavaScript code, first of all you need to make sure that web page is loaded completely.

If the web page is loaded completely you can execute JavaScript code using one of the following ways:

Executing JavaScript without returning a value

The Browser.ExecuteJavaScript(string javaScript) method executes the JavaScript code asynchronously without blocking the current thread execution. If you are not interested in receiving the result of JavaScript code, you can use this method because its return parameter is void.

// Executes the passed JavaScript code asynchronously
browser.ExecuteJavaScript("document.write('<html><title>My Title</title><body>Hello from DotNetBrowser!</body></html>');");

Executing JavaScript and returning the result

The Browser.ExecuteJavaScriptAndReturnValue(string javaScript) method executes the code described by javaScript parameter and returns the result of JavaScript code execution as JSValue. This method blocks the current thread execution until the passed JavaScript code stops its execution and return the result of the execution.

The JSValue provides access to the result of JavaScript code execution. Using the methods of JSValue you can determine whether the result value is an object, number, string or boolean value. For example, the following code demonstrates how to get a document title string value using the Browser.ExecuteJavaScriptAndReturnValue(string javaScript) method:

JSValue documentTitle = browser.ExecuteJavaScriptAndReturnValue("document.title");
// Make sure that result value is a string and read its value
if (documentTitle.IsString()) {
    Console.WriteLine("Document Title = " + documentTitle.GetString());

In this sample we check that the return JSValue is a string value, using the JSValue.IsString() method; and access the string value, using the JSValue.GetString() method.

Please avoid using the Browser.ExecuteJavaScriptAndReturnValue(String javaScript) method in the UI thread, because the passed JavaScript code can cause JavaScript Alert dialog to be shown. All the dialogs are displayed in the UI thread by default. As a result, it can cause a deadlock.