Navigation

This guide describes the navigation events and shows how to load URLs and files, filter navigation requests, work with navigation history, and so on.

Loading URL

To navigate to a resource identified by a URL, use one of the following methods:

  • INavigation.LoadUrl(string url)
  • INavigation.LoadUrl(LoadUrlParameters parameters)

Example below shows how to navigate to https://www.google.com using the INavigation.LoadUrl(string) method:

INavigation navigation = browser.Navigation;
navigation.LoadUrl("https://www.google.com");

Loading URL synchronously

The LoadUrl method sends a navigation request to the given resource and returns a Task<LoadResult> that can be used to wait until the resource is considered to be loaded completely.

If you need to block the current thread execution until the resource is loaded completely, use the Task.Wait() method:

navigation.LoadUrl("https://www.google.com").Wait();

This method blocks the current thread execution until the main frame of the resource is loaded completely or until the default 100 seconds timeout is reached.

If the navigation fails, the returned Task<LoadResult> is completed, and its Task.Result property returns LoadResult.Failed.

If the resource is not loaded within a given period, the TimeoutException exception occurs.

The web page is considered to be loaded completely when at least one of the following events, namely, FrameLoadFinished, NavigationFinished, or FrameLoadFailed occurs for the main frame.

Loading URL with POST

To load a web page by its URL and send POST data, use the INavigation.LoadUrl(LoadUrlParameters) method. The following code demonstrates how to load URL and send POST data in different formats using extra headers.

You can send a web form data in the key=value format to a web server:

navigation.LoadUrl(new LoadUrlParameters("https://google.com",
        "myKey=myValue&myKey2=myValue2"));
// If you don't specify extra headers, then the extra headers
// will be set to "Content-Type: application/x-www-form-urlencoded\n"

If you want to send some plain text, add the extra headers that instruct the web server it is a plain text:

navigation.LoadUrl(new LoadUrlParameters("https://www.google.com",
                                         "Some Text...", 
                                         new HttpHeader("Content-Type", 
                                                        "text/plain")));

You can send any data of various types. To do so, specify its Content-Type. See the code sample on sending JSON data below:

navigation.LoadUrl(new LoadUrlParameters("https://www.google.com", 
                                         "{\"title\":\"Hello\"}", 
                                         new HttpHeader("Content-Type", 
                                                        "application/json")));

Loading a file

You can use the same methods to load HTML files from the local file system by providing an absolute path to the HTML file instead of an URL. See the code sample below:

navigation.LoadUrl(Path.GetFullPath("index.html"));

Loading data

You can navigate an IFrame to the data with specified MIME type, document Base URL (for text/html only) and optional text encoding. See the code sample below:

frame.LoadData(new LoadDataParameters("<html><body>Hello</body></html>")
{
    BaseUrl = "<baseUrl>",
    MimeType = MimeType.TextHtml, 
    Replace = true,
    TextEncoding = "UTF-8"
});

Loading HTML

You can navigate IFrame to the data that represents an HTML document with the text/html MIME type.

You can load only HTML string:

frame.LoadHtml("<html><body>HTML Text</body></html>");

You can also provide additional options, such as Base URL when loading HTML:

frame.LoadHtml(new LoadHtmlParameters("<html><body>HTML Text</body></html>")
{
    BaseUrl = "<url>",
    Replace = true
}); 

Reloading

There are several options to reload the currently loaded web page:

  • Reload using HTTP cache:
navigation.Reload();
  • Reload ignoring HTTP cache:
navigation.ReloadIgnoringCache();
  • Reload using HTTP cache and check for repost:
navigation.ReloadAndCheckForRepost();
  • Reload ignoring HTTP cache and check for repost:
navigation.ReloadIgnoringCacheAndCheckForRepost();

Stopping

Use the INavigation.Stop() method to cancel any pending navigation or download operation, and stop any dynamic page elements, such as background sounds and animations. See the code sample below:

navigation.Stop();

Back & forward

DotNetBrowser allows working with the navigation back-forward history list.

When you create an IBrowser instance, it navigates to the about:blank web page by default. There is always one entry in the navigation back-forward list.

To load the previous location in the back-forward list, use the following approach:

if (navigation.CanGoBack()) {
    navigation.GoBack();
}

To load the next location in the back-forward list, use the following approach:

if (navigation.CanGoForward()) {
    navigation.GoForward();
}

To navigate to the entry at a specific index in the back-forward list, use the following approach:

if (index >=0 && index < navigation.EntryCount) {
    navigation.GoTo(index);
}

To go through the back-forward list and get the details about every navigation entry, use the following approach:

for (int index = 0; index < navigation.EntryCount; index++) {
    INavigationEntry navigationEntry = navigation.EntryAt(index);
    Console.WriteLine("URL: " + navigationEntry.Url);
    Console.WriteLine("Title: " + navigationEntry.Title);
}

To modify the back-forward list by removing the entries, use the following approach:

// Returns the number of entries in the back/forward list.
int entryCount = navigation.EntryCount;
// Remove navigation entries at index.
for (int i = entryCount - 2; i >= 0; i--) {
    bool success = navigation.RemoveEntryAt(i);
    Console.WriteLine("Navigation entry at index " + i +
            " has been removed successfully? " + success);
}

Filtering URLs

You can decide whether navigation request to a specific URL is ignored.

See the code sample below showing how to ignore navigation requests to all URLs starting with https://www.google:

navigation.StartNavigationHandler = 
    new Handler<StartNavigationParameters, StartNavigationResponse>((p) =>
    {
        // Ignore navigation requests to the URLs that start 
        // with "https://www.google"
        if (p.Url.StartsWith("https://www.google"))
        {
            return StartNavigationResponse.Start();
        }
        return StartNavigationResponse.Ignore();
    });

Filtering resources

The LoadResourceHandler handler lets you determine whether the resources such as HTML, image, JavaScript or CSS file, favicon, and others are loaded. By default, all resources are loaded. To modify the default behavior, register your own handler implementation where you decide which resources are canceled or loaded.

See the code sample below showing how to suppress all images:

engine.Network.LoadResourceHandler =
    new Handler<LoadResourceParameters, LoadResourceResponse>(p =>
    {
        if (p.ResourceType != ResourceType.Image)
        {
            return LoadResourceResponse.Cancel();
        }

        return LoadResourceResponse.Continue();
    });

Loading a web page is a complex process where navigation events are fired. The following diagram shows the order of the navigation events that might be fired when loading a web page: Navigation Events Flow

Load started

To get notifications when content loading has started, use the LoadStarted event. See the code sample below:

navigation.LoadStarted += (s, e) => {};

This event corresponds to the moment when the spinner of the tab starts spinning.

Load finished

To get notifications when content loading has finished, use the LoadFinished event. For example:

navigation.LoadFinished += (s, e) => {};

This event corresponds to the moment when the spinner of the tab stops spinning.

To get notifications when navigation has started, use the NavigationStarted event. See the code sample below:

navigation.NavigationStarted += (s, e) => 
{
    string url = e.Url;
    // Indicates whether the navigation will be performed
    // in the scope of the same document.
    bool isSameDocument = e.IsSameDocument;
};

To get notifications when navigation has stopped, use the NavigationStopped event. See the code sample below:

navigation.NavigationStopped += (s, e) => {};

This event is fired when navigation is stopped using the Navigation.stop() method.

To get notifications when navigation has been redirected to a new URL, use the NavigationRedirected event. See the code sample below:

navigation.NavigationRedirected += (s, e) => {
    // The navigation redirect URL.
    string url = e.Url;
};

To get notifications when navigation has finished, use the NavigationFinished event. See the code sample below:

navigation.NavigationFinished += (s, e) => {
    string url = e.Url;
    IFrame frame = e.Frame;
    bool hasCommitted = e.HasCommitted;
    bool isSameDocument = e.IsSameDocument;
    bool isErrorPage = e.IsErrorPage;
    if (isErrorPage) {
        NetError error = e.ErrorCode;
    }
};

This event is fired when navigation is committed, aborted, or replaced by a new one. To know if the navigation has committed, use NavigationFinishedEventArgs.HasCommitted. To know if the navigation resulted in an error page, use NavigationFinishedEventArgs.IsErrorPage.

If the event is called because the navigation committed, the document load will still be ongoing.

The event is fired by same-document (in the scope of the same document) navigations, such as fragment navigations or window.history.pushState()/window.history.replaceState(), which does not result in a document change. Use NavigationFinishedEventArgs.IsSameDocument property to check if it is a same-document navigation.

Frame load finished

To get notifications when content loading in the IFrame has finished, use the FrameLoadFinished event. See the code sample below:

navigation.FrameLoadFinished += (s, e) =>
{
    string url = e.ValidatedUrl;
    IFrame frame = e.Frame;
};

This event corresponds to the moment when the content in the Frame has been loaded completely.

Frame load failed

To get notifications when content loading in the Frame has failed for some reason, use the FrameLoadFailed event. See the code sample below:

navigation.FrameLoadFailed += (s, e) =>
{
    string url = e.ValidatedUrl;
    NetError error = e.ErrorCode;
};

Frame document load finished

To get notifications when the document loading in the Frame has finished, use the FrameDocumentLoadFinished event. See the code sample below:

navigation.FrameDocumentLoadFinished += (s, e) => 
{
    IFrame frame = e.Frame;
};

At this point, deferred scripts were executed, and the content scripts marked document_end get injected into the frame.

Go Top