Introduction
Installation
Guides
- Engine
- Profile
- Browser
- BrowserView
- Navigation
- Content
- Context menu
- DOM
- JavaScript
- Pop-ups
- Dialogs
- Downloads
- Chrome extensions
- Network
- Cache
- Cookies
- Proxy
- Authentication
- Permissions
- Plugins
- Printing
- Passwords
- User data profiles
- Credit cards
- Media
- Zoom
- Spell checker
- Deployment
- Chromium
Troubleshooting
- Logging
- Common exceptions
- Application does not terminate
- Video does not play
- Cannot sign in to Google account
- User data is not stored
- Color scheme
- Startup failure
- Slow startup on Windows
- Unresponsive .NET Application
- Unexpected Chromium process termination
- Unexpected behavior
- Windows 7/8/8.1 end of support
Migration
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");
Dim navigation As INavigation = 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<NavigationResult>
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();
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<NavigationResult>
is completed, and its Task.Result
property returns the details about the possible navigation failure.
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://postman-echo.com/post")
{
UploadData = new FormData(new Dictionary<string, string>()
{
{"key", "value"}
})
});
navigation.LoadUrl(New LoadUrlParameters("https://postman-echo.com/post") With {
.UploadData = New FormData(New Dictionary(Of String, String)() From {
{"key", "value"}
})
})
You need to specify explicitly “Content-Type” header for each request type.
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://postman-echo.com/post")
{
UploadData = new TextData("Some text..."),
HttpHeaders = new[]
{
new HttpHeader("Content-Type", "text/plain")
}
});
navigation.LoadUrl(New LoadUrlParameters("https://postman-echo.com/post") With {
.UploadData = New TextData("Some text..."),
.HttpHeaders =
{
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://postman-echo.com/post")
{
PostData = "{\"title\":\"Hello\"}",
HttpHeaders = new[]
{
new HttpHeader("Content-Type", "application/json")
}
});
navigation.LoadUrl(New LoadUrlParameters("https://postman-echo.com/post") With {
.PostData = "{""title"":""Hello""}",
.HttpHeaders =
{
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"));
navigation.LoadUrl(Path.GetFullPath("index.html"))
Loading HTML
To load HTML into browser, you can create a data:
encoded URI and then load it using the regular LoadUrl
call. Here is an example:
var html = "<html><head></head><body><h1>Html Encoded in URL!</h1></body></html>";
var base64EncodedHtml = Convert.ToBase64String(Encoding.UTF8.GetBytes(html));
browser.Navigation.LoadUrl("data:text/html;base64," + base64EncodedHtml).Wait();
Dim html = "<html><head></head><body><h1>Html Encoded in URL!</h1></body></html>"
Dim base64EncodedHtml = Convert.ToBase64String(Encoding.UTF8.GetBytes(html))
browser.Navigation.LoadUrl("data:text/html;base64," & base64EncodedHtml).Wait()
Chromium limits data-encoded URIs to a maximum length of 2MB.
However, the base URL cannot be set when using this approach.
Another possible approach is to register a Scheme
with a handler and intercept the corresponding request to provide the HTML. See the corresponding article.
Reloading
There are several options to reload the currently loaded web page:
- Reload using HTTP cache:
navigation.Reload();
navigation.Reload()
- Reload ignoring HTTP cache:
navigation.ReloadIgnoringCache();
navigation.ReloadIgnoringCache()
- Reload using HTTP cache and check for repost:
navigation.ReloadAndCheckForRepost();
navigation.ReloadAndCheckForRepost()
- Reload ignoring HTTP cache and check for repost:
navigation.ReloadIgnoringCacheAndCheckForRepost();
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();
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();
}
If navigation.CanGoBack() Then
navigation.GoBack()
End If
To load the next location in the back-forward list, use the following approach:
if (navigation.CanGoForward()) {
navigation.GoForward();
}
If navigation.CanGoForward() Then
navigation.GoForward()
End If
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);
}
If index >=0 AndAlso index < navigation.EntryCount Then
navigation.GoTo(index)
End If
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);
}
For index As Integer = 0 To navigation.EntryCount - 1
Dim navigationEntry As INavigationEntry = navigation.EntryAt(index)
Console.WriteLine("URL: " & navigationEntry.Url)
Console.WriteLine("Title: " & navigationEntry.Title)
Next
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);
}
' Returns the number of entries in the back/forward list.
Dim entryCount As Integer = navigation.EntryCount
' Remove navigation entries at index.
For i As Integer = entryCount - 2 To 0 Step -1
Dim success As Boolean = navigation.RemoveEntryAt(i)
Console.WriteLine("Navigation entry at index " & i &
" has been removed successfully? " & success)
Next
Overscroll history navigation
In the hardware-accelerated rendering mode, DotNetBrowser allows navigating back/forward with a left/right swipe on devices with the touch screen. By default, the overscroll navigation is disabled. To enable it, use the IBrowserSettings.OverscrollHistoryNavigationEnabled
property:
browser.Settings.OverscrollHistoryNavigationEnabled = true;
browser.Settings.OverscrollHistoryNavigationEnabled = True
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.Ignore();
}
return StartNavigationResponse.Start();
});
navigation.StartNavigationHandler =
New Handler(Of StartNavigationParameters, StartNavigationResponse)(Function(p)
' Ignore navigation requests to the URLs that start
' with "https://www.google".
If p.Url.StartsWith("https://www.google") Then
Return StartNavigationResponse.Ignore()
End If
Return StartNavigationResponse.Start()
End Function)
Filtering resources
The SendUrlRequestHandler
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.SendUrlRequestHandler =
new Handler<SendUrlRequestParameters, SendUrlRequestResponse>(p =>
{
if (p.UrlRequest.ResourceType == ResourceType.Image)
{
return SendUrlRequestResponse.Cancel();
}
return SendUrlRequestResponse.Continue();
});
engine.Network.SendUrlRequestHandler =
New Handler(Of SendUrlRequestParameters, SendUrlRequestResponse)(Function(p)
If p.UrlRequest.ResourceType = ResourceType.Image Then
Return SendUrlRequestResponse.Cancel()
End If
Return SendUrlRequestResponse.Continue()
End Function)
Navigation events
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:
Load started
To get notifications when content loading has started, use the LoadStarted
event. See the code sample below:
navigation.LoadStarted += (s, e) => {};
AddHandler navigation.LoadStarted, Sub(s, e)
End Sub
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) => {};
AddHandler navigation.LoadFinished, Sub(s, e)
End Sub
This event corresponds to the moment when the spinner of the tab stops spinning.
Load progress
The LoadProgressChanged
event allows getting notifications about load progress:
navigation.LoadProgressChanged += (s, e) =>
{
// The value indicating the loading progress of the web page.
double progress = e.Progress;
};
AddHandler navigation.LoadProgressChanged, Sub(s, e)
' The value indicating the loading progress of the web page.
Dim progress As Double = e.Progress
End Sub
Navigation started
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;
};
AddHandler navigation.NavigationStarted, Sub(s, e)
Dim url As String = e.Url
' Indicates whether the navigation will be performed
' in the scope of the same document.
Dim isSameDocument As Boolean = e.IsSameDocument
End Sub
Navigation stopped
To get notifications when navigation has stopped, use the NavigationStopped
event. See the code sample below:
navigation.NavigationStopped += (s, e) => {};
AddHandler navigation.NavigationStopped, Sub(s, e)
End Sub
This event is fired when navigation is stopped using the Navigation.stop()
method.
Navigation redirected
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;
};
AddHandler navigation.NavigationRedirected, Sub(s, e)
' The navigation redirect URL.
Dim url As String = e.Url
End Sub
Navigation finished
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;
}
};
AddHandler navigation.NavigationFinished, Sub(s, e)
Dim url As String = e.Url
Dim frame As IFrame = e.Frame
Dim hasCommitted As Boolean = e.HasCommitted
Dim isSameDocument As Boolean = e.IsSameDocument
Dim isErrorPage As Boolean = e.IsErrorPage
If isErrorPage Then
Dim [error] As NetError = e.ErrorCode
End If
End Sub
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;
};
AddHandler navigation.FrameLoadFinished, Sub(s, e)
Dim url As String = e.ValidatedUrl
Dim frame As IFrame = e.Frame
End Sub
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;
};
AddHandler navigation.FrameLoadFailed, Sub(s, e)
Dim url As String = e.ValidatedUrl
Dim [error] As NetError = e.ErrorCode
End Sub
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;
};
AddHandler navigation.FrameDocumentLoadFinished, Sub(s, e)
Dim frame As IFrame = e.Frame
End Sub
At this point, deferred scripts were executed, and the content scripts marked document_end get injected into the frame.
Custom error page
To override standard Chromium error pages, use ShowHttpErrorPageHandler
and ShowNetErrorPageHandler
handlers for HTTP (e.g. 404 Not Found) or network errors (e.g. ERR_CONNECTION_REFUSED) respectively. See examples below:
HTTP error page
browser.Navigation.ShowHttpErrorPageHandler =
new Handler<ShowHttpErrorPageParameters, ShowHttpErrorPageResponse>(arg =>
{
string url = arg.Url;
HttpStatusCode httpStatusCode = arg.HttpStatus;
return ShowHttpErrorPageResponse.Show("HTTP Error web page:" + httpStatusCode);
});
browser.Navigation.ShowHttpErrorPageHandler =
New Handler(Of ShowHttpErrorPageParameters, ShowHttpErrorPageResponse)(Function(arg)
Dim url As String = arg.Url
Dim httpStatusCode As HttpStatusCode = arg.HttpStatus
Return ShowHttpErrorPageResponse.Show("HTTP Error web page:" & httpStatusCode)
End Function)
Network error page
browser.Navigation.ShowNetErrorPageHandler =
new Handler<ShowNetErrorPageParameters, ShowNetErrorPageResponse>(arg =>
{
return ShowNetErrorPageResponse.Show("Network error web page");
});
browser.Navigation.ShowNetErrorPageHandler =
New Handler(Of ShowNetErrorPageParameters, ShowNetErrorPageResponse)(Function(arg)
Return ShowNetErrorPageResponse.Show("Network error web page")
End Function)
Custom error pages provided by the servers are not intercepted by these handlers and cannot be overridden using this functionality. The above handlers are invoked only for overriding the default Chromium error pages.