Browser

This guide describes how to create, use, and close Browser.

Refer to the Architecture guide for more information on DotNetBrowser architecture, its main components, and their interaction.

Creating a browser

To create a new IBrowser instance, use the IEngine.CreateBrowser() method. For example:

IBrowser browser = engine.CreateBrowser();

This method performs the following actions:

  1. Creates a new IBrowser instance.
  2. Loads the about:blank web page in it and waits until the web page is completely loaded.

Disposing a browser

The IBrowser instance runs in the Chromium Main process and allocates memory and system resources to be released. When an IBrowser instance is no longer needed, dispose it using the IBrowser.Dispose() method. As a result, all the allocated memory and system resources are released. See the code sample below:

IBrowser browser = engine.CreateBrowser();
//...
browser.Dispose();

An attempt to use an already disposed IBrowser instance leads to the ObjectDisposedException.

The IBrowser instance is disposed automatically in the following cases:

  1. When its parent IEngine instance is disposed or crashed unexpectedly.
  2. When this IBrowser instance is a pop-up that is closed from JavaScript using window.close().

Use the Disposed event to be notified when the IBrowser instance is disposed. See the code sample below:

browser.Disposed += (sender, event => {});

Use the IsDisposed property to check whether IBrowser is already disposed:

bool disposed = browser.IsDisposed;

Browser size

By default, IBrowser size is empty. If you want to work with DOM or Find Text on a web page, set the browser size first.

To update the size of the IBrowser, please use its Size property. See the code sample below:

browser.Size = new Size(800, 600);

This method notifies Chromium that the size of the IBrowser instance has been changed. Chromium will update the DOM layout of the loaded web page and repaint its content asynchronously. It might take some time for the web page to be repainted after the property is set.

Browser settings

It is possible to customize the browser settings through the IBrowser.Settings property. The browser settings can be used to disable images, plugins or JavaScript in the browser, hide scrollbars, disable application cache. See the code sample below:

// Disable all scripts.
browser.Settings.JavaScriptEnabled = false;

Specifying WebRTC IP Handling Policy

DotNetBrowser allows to customize WebRTC IP handling policy. These are WebRTC policies available in DotNetBrowser:

  • Default - default Chromium behavior. When this policy is set, WebRTC can enumerate all interfaces and bind them to discover public interfaces.

  • DefaultPublicInterfacesOnly - tells the browser to send WebRTC traffic using the default public network adapter. This will be the VPN adapter for system-VPN users. WebRTC must use only the default route used by http.

  • DefaultPublicAndPrivateInterfaces - same as DefaultPublicInterfacesOnly except it allows WebRTC traffic through the default private interface to your local network as well.

  • DisableNonProxiedUdp - disables non-proxied UDP and forces proxy. This policy forces the use of a proxy and only allows WebRTC traffic over UDP proxies. It effectively disables WebRTC communication for most users depending on UDP proxy usage.

The following sample code demonstrates how to configure the WebRTC IP handling policy for a Browser instance:

browser.Settings.WebRtcIpHandlingPolicy = 
    WebRtcIpHandlingPolicy.DisableNonProxiedUdp;

User Agent

You can override the default User Agent string and configure IBrowser to use a custom string. See the code sample below:

browser.UserAgent = "<user-agent>";

The same property can be used to get the current user agent string:

string userAgent = browser.UserAgent;

Remote debugging URL

To get the remote debugging URL for a web page loaded in a particular IBrowser instance, use the following approach:

string url = browser.DevTools.RemoteDebuggingUrl;

This approach returns a valid URL only if the IEngine is configured with the Remote Debugging Port. Otherwise, the property value is null.

Mouse and keyboard events

DotNetBrowser allows to intercept the mouse and keyboard events before they are sent to the web page using the following handlers:

  • IBrowser.Mouse.Entered.Handler
  • IBrowser.Mouse.Exited.Handler
  • IBrowser.Mouse.Pressed.Handler
  • IBrowser.Mouse.Released.Handler
  • IBrowser.Mouse.Moved.Handler
  • IBrowser.Mouse.WheelMoved.Handler
  • IBrowser.Keyboard.KeyPressed.Handler
  • IBrowser.Keyboard.KeyTyped.Handler
  • IBrowser.Keyboard.KeyReleased.Handler

The following code sample demonstrates how to suppress mouse wheel events:

browser.Mouse.WheelMoved.Handler = 
    new Handler<IMouseWheelMovedEventArgs, InputEventResponse>(e =>
    {
        return InputEventResponse.Suppress;
    });

You can use these handlers to get the notifications about the mouse and keyboard events to implement hotkeys in your application. You can also suppress the default shortcuts such as Ctrl+C. See the code sample below:

browser.Keyboard.KeyPressed.Handler = 
    new Handler<IKeyPressedEventArgs, InputEventResponse>(e =>
    {
        bool keyCodeC = e.VirtualKey == KeyCode.VkC;
        bool controlDown = e.Modifiers.ControlDown;
        if (controlDown && keyCodeC) 
        {
            return InputEventResponse.Suppress;
        }
        return InputEventResponse.Proceed;
    });

Simulating user input

DotNetBrowser allows to simulate mouse and keyboard input. Simulation is available in both off-screen and hardware-accelerated rendering modes for WPF and Windows Forms.

You can simulate input by raising mouse and keyboard events. For example, here is how to simulate typing “H”:

IKeyboard keyboard = browser.Keyboard;
KeyCode key = KeyCode.VkH;
string keyChar = "H";

KeyPressedEventArgs keyDownEventArgs = new KeyPressedEventArgs
{
    KeyChar = keyChar,
    VirtualKey = key
};

KeyTypedEventArgs keyPressEventArgs = new KeyTypedEventArgs
{
    KeyChar = keyChar,
    VirtualKey = key
};
KeyReleasedEventArgs keyUpEventArgs = new KeyReleasedEventArgs
{
    VirtualKey = key
};

keyboard.KeyPressed.Raise(keyDownEventArgs);
keyboard.KeyTyped.Raise(keyPressEventArgs);
keyboard.KeyReleased.Raise(keyUpEventArgs);

You can simulate the mouse click by raising IMouse.Moved, IMouse.Pressed, and IMouse.Released events in a sequence. For example, here is how to simulate a single click:

IMouse mouse = browser.Mouse;
MouseButton mouseButton = MouseButton.Left;
Point location = new Point(10, 10);

MouseMovedEventArgs moveEvent = new MouseMovedEventArgs
{
    Location = location
};

MousePressedEventArgs pressEvent = new MousePressedEventArgs
{
    Location = location,
    Button = mouseButton,
    ClickCount = 1
};

MouseReleasedEventArgs releaseEvent = new MouseReleasedEventArgs
{
    Button = mouseButton,
    ClickCount = 1,
    Location = location
};

mouse.Moved.Raise(moveEvent);
Thread.Sleep(200);
mouse.Pressed.Raise(pressEvent);
Thread.Sleep(200);
mouse.Released.Raise(releaseEvent);

Title events

TitleChanged event indicates that the title of a document in the main frame has been changed.

To get notifications when a document’s title change, use the TitleChanged listener as shown in the code sample below:

browser.TitleChanged += delegate (object sender, TitleChangedEventArgs e)
{
    string mainDocumentTitle = e.Title;
};

Status events

When the user moves the cursor over a link, Chromium engine displays its URL in the status bar. JavaScript code can change the text in the status bar programmatically using the window.statusproperty as well. The DotNetBrowser API provides functionality for getting notifications about status bar text changes.

StatusChanged event indicates that the status bar text has been changed.

The code sample below demonstrates how to use this functionality:

browser.StatusChanged += delegate(object sender, StatusChangedEventArgs e)
{
    string statusText = e.Text;
};

Render process termination event

Each IBrowser instance is bound to a separate native process where the web page is rendered. By default, Chromium creates a render process for each instance of a website the user visits. This ensures that pages from different websites are rendered independently, and separate visits to the same website are also isolated from each other. Thus, failures (for example, renderer crashes) or heavy resource usage in one instance of a site does not affect the rest of the browser.

Sometimes this process can terminate unexpectedly. To receive notifications about render process termination, you can subscribe to the IBrowser.RenderProcessTerminated event. The RenderProcessTerminatedEventArgs.ExitCode value can be used to determine whether this is an expected process termination or a failure.

When you receive a notification about the unexpected render process termination, you can display a “sad” icon like Google Chrome does, for example, to inform the user about this particular instance crash.

If you refresh or load the same or another URL after the crash, the rendering process and the IBrowser instance is restored:

browser.RenderProcessTerminated += (sender, e) =>
{
    int exitCode = e.ExitCode;
    if (exitCode != 0)
    {
        //render process terminated unexpectedly
    }
};
Go Top