WebView2.DevTools.Dom 3.0.0

There is a newer version of this package available.
See the version list below for details.
dotnet add package WebView2.DevTools.Dom --version 3.0.0                
NuGet\Install-Package WebView2.DevTools.Dom -Version 3.0.0                
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="WebView2.DevTools.Dom" Version="3.0.0" />                
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add WebView2.DevTools.Dom --version 3.0.0                
#r "nuget: WebView2.DevTools.Dom, 3.0.0"                
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install WebView2.DevTools.Dom as a Cake Addin
#addin nuget:?package=WebView2.DevTools.Dom&version=3.0.0

// Install WebView2.DevTools.Dom as a Cake Tool
#tool nuget:?package=WebView2.DevTools.Dom&version=3.0.0                

WebView2 DevTools DOM

Nuget Nuget GitHub Sponsors

WebView2 DevTools Dom is a port of puppeteer-sharp by Darío Kondratiuk that has been adapted specifically for use with WebView2.

  • Direct communication with the CoreWebView2 via the DevTools protocol (no need to open a Remote Debugging Port).
  • 1:1 mapping of WebView2DevToolsContext and CoreWebView2 (create a single WebView2DevToolsContext per CoreWebView2 instance)
  • The primary focus of this project is DOM access/manipulation and Javascript execution/evaluation.
  • Only a subset of the Puppeteer Sharp features were ported (It maybe possible to port additional features if sufficent user demand).

Sponsorware

This project has adopted a variant of the Sponsorware open source model. To ensure the project maintainer/developer (@amaitland) can support the project the source will be released under an MIT license when the target of 25 sponsors signup to the WebView2 DevTools Dom Supporter tier here on GitHub. Sponsors will get priority support and automatically gain access to the project source. Everyone is free to download and use the Nuget package.

The xUnit tests are avaliable as part of this repository.

Prerequisites

Questions and Support

Need priority support? Signup to the WebView2 DevTools Dom Supporter tier on GitHub Sponsors.

Usage

Quick Start Tutorial (YouTube)

WebView2 DevTools Dom Quick Start tutorial on Youtube

WebView2DevToolsContext

The WebView2DevToolsContext class is the main entry point into the library and can be created from a CoreWebView2 instance. Only a single WebView2DevToolsContext should exist at any given time, when you are finished them make sure you dispose via DisposeAsync.

// Add using WebView2.DevTools.Dom; to get access to the
// CreateDevToolsContextAsync extension method
var devtoolsContext = await coreWebView2.CreateDevToolsContextAsync();

// Manually dispose of context (only DisposeAsync is supported as the whole API is async)
await devToolsContext.DisposeAsync();
// Dispose automatically via await using
// https://docs.microsoft.com/en-us/dotnet/standard/garbage-collection/implementing-disposeasync#using-async-disposable
await using var devtoolsContext = await coreWebView2.CreateDevToolsContextAsync();

DOM Access

Read/write to the DOM

<a id='snippet-queryselector'></a>

// Add using WebView2.DevTools.Dom; to get access to the
// CreateDevToolsContextAsync extension method

coreWebView2.NavigationCompleted += async (sender, args) =>
{
    if(args.IsSuccess)
    {
        // WebView2DevToolsContext implements IAsyncDisposable and can be Disposed
        // via await using or await devToolsContext.DisposeAsync();
        // https://docs.microsoft.com/en-us/dotnet/standard/garbage-collection/implementing-disposeasync#using-async-disposable
        await using var devToolsContext = await coreWebView2.CreateDevToolsContextAsync();

        // Get element by Id
        // https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector
        var element = await devToolsContext.QuerySelectorAsync<HtmlElement>("#myElementId");

        //Strongly typed element types
        //Only a subset of element types have been added so far, use HtmlElement as a generic type for all others
        var htmlDivElement = await devToolsContext.QuerySelectorAsync<HtmlDivElement>("#myDivElementId");
        var htmlSpanElement = await devToolsContext.QuerySelectorAsync<HtmlSpanElement>("#mySpanElementId");
        var htmlSelectElement = await devToolsContext.QuerySelectorAsync<HtmlSelectElement>("#mySelectElementId");
        var htmlInputElement = await devToolsContext.QuerySelectorAsync<HtmlInputElement>("#myInputElementId");
        var htmlFormElement = await devToolsContext.QuerySelectorAsync<HtmlFormElement>("#myFormElementId");
        var htmlAnchorElement = await devToolsContext.QuerySelectorAsync<HtmlAnchorElement>("#myAnchorElementId");
        var htmlImageElement = await devToolsContext.QuerySelectorAsync<HtmlImageElement>("#myImageElementId");
        var htmlTextAreaElement = await devToolsContext.QuerySelectorAsync<HtmlImageElement>("#myTextAreaElementId");
        var htmlButtonElement = await devToolsContext.QuerySelectorAsync<HtmlButtonElement>("#myButtonElementId");
        var htmlParagraphElement = await devToolsContext.QuerySelectorAsync<HtmlParagraphElement>("#myParagraphElementId");
        var htmlTableElement = await devToolsContext.QuerySelectorAsync<HtmlTableElement>("#myTableElementId");

        // Get a custom attribute value
        var customAttribute = await element.GetAttributeAsync<string>("data-customAttribute");

        //Set innerText property for the element
        await element.SetInnerTextAsync("Welcome!");

        //Get innerText property for the element
        var innerText = await element.GetInnerTextAsync();
        //Can also be acessed via calling GetPropertyValueAsync
        //Can use this method to get any property that isn't currently mapped
        innerText = await element.GetInnerTextAsync();

        //Get all child elements
        var childElements = await element.QuerySelectorAllAsync("div");

        //Change CSS style background colour
        await element.EvaluateFunctionAsync("e => e.style.backgroundColor = 'yellow'");

        //Type text in an input field
        await element.TypeAsync("Welcome to my Website!");

        //Scroll Element into View (if needed)
        //Can optional specify a Rect to be scrolled into view, relative to the node's border box,
        //in CSS pixels. When omitted, center of the node will be used
        await element.ScrollIntoViewIfNeededAsync();

        //Click The element
        await element.ClickAsync();

        // Simple way of chaining method calls together when you don't need a handle to the HtmlElement
        var htmlButtonElementInnerText = await devToolsContext.QuerySelectorAsync<HtmlButtonElement>("#myButtonElementId")
            .AndThen(x => x.GetInnerTextAsync());

        //Event Handler
        //Expose a function to javascript, functions persist across navigations
        //So only need to do this once
        await devToolsContext.ExposeFunctionAsync("jsAlertButtonClick", () =>
        {
            _ = devToolsContext.EvaluateExpressionAsync("window.alert('Hello! You invoked window.alert()');");
        });

        var jsAlertButton = await devToolsContext.QuerySelectorAsync("#jsAlertButton");

        //Write up the click event listner to call our exposed function
        _ = jsAlertButton.AddEventListenerAsync("click", "jsAlertButtonClick");

        //Get a collection of HtmlElements
        var divElements = await devToolsContext.QuerySelectorAllAsync<HtmlDivElement>("div");

        foreach (var div in divElements)
        {
            // Get a reference to the CSSStyleDeclaration
            var style = await div.GetStyleAsync();

            //Set the border to 1px solid red
            await style.SetPropertyAsync("border", "1px solid red", important: true);

            await div.SetAttributeAsync("data-customAttribute", "123");
            await div.SetInnerTextAsync("Updated Div innerText");
        }

        //Using standard array
        var tableRows = await htmlTableElement.GetRowsAsync().ToArrayAsync();

        foreach(var row in tableRows)
        {
            var cells = await row.GetCellsAsync().ToArrayAsync();
            foreach(var cell in cells)
            {
                var newDiv = await devToolsContext.CreateHtmlElementAsync<HtmlDivElement>("div");
                await newDiv.SetInnerTextAsync("New Div Added!");
                await cell.AppendChildAsync(newDiv);
            }
        }

        //Get a reference to the HtmlCollection and use async enumerable
        //Requires Net Core 3.1 or higher
        var tableRowsHtmlCollection = await htmlTableElement.GetRowsAsync();

        await foreach (var row in tableRowsHtmlCollection)
        {
            var cells = await row.GetCellsAsync();
            await foreach (var cell in cells)
            {
                var newDiv = await devToolsContext.CreateHtmlElementAsync<HtmlDivElement>("div");
                await newDiv.SetInnerTextAsync("New Div Added!");
                await cell.AppendChildAsync(newDiv);
            }
        }
    }
};

<sup><a href='/WebView2.DevTools.Dom.Tests/QuerySelectorTests/DevToolsContextQuerySelectorTests.cs#L20-L144' title='Snippet source file'>snippet source</a> | <a href='#snippet-queryselector' title='Start of snippet'>anchor</a></sup>

<a id='snippet-getnavigationhistoryasync'></a>

// Add using WebView2.DevTools.Dom; to get access to the
// CreateDevToolsContextAsync extension method

// WebView2DevToolsContext implements IAsyncDisposable and can be Disposed
// via await using or await devToolsContext.DisposeAsync();
// Only DisposeAsync is supported. It's very important the WebView2DevToolsContext is Disposed
// When you have finished. Only create a single instance at a time, reuse an instance rather than
// creaeting a new WebView2DevToolsContext. Dispose the old WebView2DevToolsContext instance before
// creating a new instance if you need to manage the lifespan manually.
// https://docs.microsoft.com/en-us/dotnet/standard/garbage-collection/implementing-disposeasync#using-async-disposable
await using var devtoolsContext = await coreWebView2.CreateDevToolsContextAsync();

//Get Histroy entries
var history = await DevToolsContext.GetNavigationHistoryAsync();

//Get the first and navigate
var firstEntry = history.Entries.First();

var title = firstEntry.Title;
var url = firstEntry.Url;
var transitionType = firstEntry.TransitionType;

await DevToolsContext.NavigateToHistoryEntryAsync(firstEntry);

<sup><a href='/WebView2.DevTools.Dom.Tests/DevToolsContextTests/NavigationHistoryTests.cs#L21-L46' title='Snippet source file'>snippet source</a> | <a href='#snippet-getnavigationhistoryasync' title='Start of snippet'>anchor</a></sup>

Inject HTML

<a id='snippet-setcontentasync'></a>

// Add using WebView2.DevTools.Dom; to get access to the
// CreateDevToolsContextAsync extension method

// WebView2DevToolsContext implements IAsyncDisposable and can be Disposed
// via await using or await devToolsContext.DisposeAsync();
// Only DisposeAsync is supported. It's very important the WebView2DevToolsContext is Disposed
// When you have finished. Only create a single instance at a time, reuse an instance rather than
// creaeting a new WebView2DevToolsContext. Dispose the old WebView2DevToolsContext instance before
// creating a new instance if you need to manage the lifespan manually.
// https://docs.microsoft.com/en-us/dotnet/standard/garbage-collection/implementing-disposeasync#using-async-disposable
await using var devtoolsContext = await coreWebView2.CreateDevToolsContextAsync();
await devtoolsContext.SetContentAsync("<div>My Receipt</div>");
var result = await devtoolsContext.GetContentAsync();

<sup><a href='/WebView2.DevTools.Dom.Tests/DevToolsContextTests/SetContentTests.cs#L22-L37' title='Snippet source file'>snippet source</a> | <a href='#snippet-setcontentasync' title='Start of snippet'>anchor</a></sup>

Evaluate Javascript

<a id='snippet-evaluate'></a>

// Add using WebView2.DevTools.Dom; to get access to the
// CreateDevToolsContextAsync extension method

await webView2Browser.EnsureCoreWebView2Async();

// WebView2DevToolsContext implements IAsyncDisposable and can be Disposed
// via await using or await devToolsContext.DisposeAsync();
// https://docs.microsoft.com/en-us/dotnet/standard/garbage-collection/implementing-disposeasync#using-async-disposable
await using var devToolsContext = await webView2Browser.CoreWebView2.CreateDevToolsContextAsync();
await devToolsContext.IgnoreCertificateErrorsAsync(true);
var seven = await devToolsContext.EvaluateExpressionAsync<int>("4 + 3");
// Can evaluate a function that returns a Promise
var fourtyTwo = await devToolsContext.EvaluateFunctionAsync<int>("() => Promise.resolve(42)");
// Pass in arguments to a function, including references to HtmlElements and JavascriptHandles
var someObject = await devToolsContext.EvaluateFunctionAsync<dynamic>("(value) => ({a: value})", 5);
System.Console.WriteLine(someObject.a);

<sup><a href='/WebView2.DevTools.Dom.Tests/QuerySelectorTests/ElementHandleQuerySelectorEvalTests.cs#L17-L35' title='Snippet source file'>snippet source</a> | <a href='#snippet-evaluate' title='Start of snippet'>anchor</a></sup>

NOT YET SUPPORTED

  • Drag Interception/Events
  • Print to PDF
Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 was computed.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed. 
.NET Core netcoreapp3.1 is compatible. 
.NET Framework net462 is compatible.  net463 was computed.  net47 was computed.  net471 was computed.  net472 was computed.  net48 was computed.  net481 was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
4.0.1 1,474 3/16/2024
3.0.1 4,936 10/30/2022
3.0.0 1,278 7/25/2022
3.0.0-beta01 408 5/20/2022
2.0.2 1,134 4/11/2022
2.0.1 657 3/28/2022
2.0.0 642 3/25/2022
1.0.6 649 3/21/2022
1.0.5 627 3/21/2022

DOM API is now generated, greatly improved number of elements supported with more methods and properties mapped.