WebviewBind 1.0.0

There is a newer version of this package available.
See the version list below for details.
dotnet add package WebviewBind --version 1.0.0
                    
NuGet\Install-Package WebviewBind -Version 1.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="WebviewBind" Version="1.0.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="WebviewBind" Version="1.0.0" />
                    
Directory.Packages.props
<PackageReference Include="WebviewBind" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add WebviewBind --version 1.0.0
                    
#r "nuget: WebviewBind, 1.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.
#:package WebviewBind@1.0.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=WebviewBind&version=1.0.0
                    
Install as a Cake Addin
#tool nuget:?package=WebviewBind&version=1.0.0
                    
Install as a Cake Tool

WebviewBind

A powerful C# source generator that simplifies bidirectional communication between JavaScript and C# in WebView2 applications. Automatically generates message dispatch infrastructure, enabling seamless JavaScript-to-C# method calls with zero boilerplate.

Features

  • 🚀 Zero Boilerplate: Source generator automatically handles WebView2 message routing
  • 🔄 Bidirectional Communication: Call C# methods from JavaScript via InvokeHostMethod()
  • ⚡ Async Support: Fully supports Task and Task<T> methods for non-blocking operations
  • 📝 Strong Typing: Full type safety with automatic JSON serialization/deserialization
  • 🎯 Simple Attribute-Based API: Just mark methods with [WebviewExport]
  • 💻 WPF Ready: Complete working example with WPF + WebView2 integration
  • 📦 NETStandard 2.0 Compatible: Works with modern .NET frameworks

How It Works

Architecture

  1. Attribute Decoration: Mark C# methods with [WebviewExport] to expose them to JavaScript
  2. Source Generation: The WebviewExportGenerator analyzes your code at compile-time
  3. Message Dispatch: Generated code handles JSON serialization and async method invocation
  4. JavaScript Bridge: Simple InvokeHostMethod() API for calling exported methods

Method Types Supported

  • Synchronous methods: Return values immediately

    [WebviewExport]
    private string GetGreeting(string name) => $"Hello {name}!";
    
  • Async methods (Task<T>): Await-able with return values

    [WebviewExport]
    private async Task<string> GetMessageAsync(string input)
    {
        await Task.Delay(2000);
        return $"Processed: {input}";
    }
    
  • Async methods (Task): Fire-and-forget with completion tracking

    [WebviewExport]
    private async Task ProcessDataAsync(string data)
    {
        await Task.Delay(1000);
        // Do work...
    }
    

Quick Start

1. Mark Your Container Class

[WebviewBind.WebviewContainer]
public partial class MainWindow : Window
{
    // Your methods go here
}

2. Export Methods

[WebviewBind.WebviewExport]
private string GetGreeting(string userName)
{
    return $"Hello {userName}!";
}

[WebviewBind.WebviewExport]
private async Task<string> FetchDataAsync(string id)
{
    // Async operation
    var data = await FetchFromDatabaseAsync(id);
    return data;
}

3. Register Handler in CodeBehind

private async void OnLoaded(object sender, RoutedEventArgs args)
{
    await WebView.EnsureCoreWebView2Async();
    RegisterWebviewHandler(WebView.CoreWebView2);  // Register generated handler
    WebView.Source = new Uri("file:///path/to/index.html");
}

4. Call from JavaScript

// Simple call
const greeting = await InvokeHostMethod('GetGreeting', 'Alice');
console.log(greeting);  // "Hello Alice!"

// Async call
const result = await InvokeHostMethod('FetchDataAsync', '123');
console.log(result);

Project Structure

src/
├── WebviewBind/
│   ├── WebviewExportGenerator.cs       # Main source generator
│   └── WebviewBind.csproj
├── Examples/
│   └── WpfWithHtml/
│       ├── MainWindow.xaml.cs          # WPF container with exported methods
│       ├── WpfWithHtml.csproj
│       └── WebFiles/
│           ├── index.html              # Test page with method examples
│           ├── styles.css              # Styles
│           └── js/
│               └── webview-bridge.js   # JavaScript bridge
└── src-web/
    └── js/
        └── webview-bridge.js           # Shared JavaScript bridge

WPF Example

The WpfWithHtml project demonstrates:

  • GetGreeting(string): Synchronous method returning a greeting
  • OpenLoadFileDialog(): Synchronous method showing a file picker dialog
  • GetMessageAsync(string): Asynchronous method with 2-second delay

The example HTML page includes:

  • Input fields for testing each method
  • Real-time status display (success/failure)
  • Activity log showing all invocations

Running the Example

  1. Build the solution: dotnet build
  2. Run the WPF app: dotnet run --project src/Examples/WpfWithHtml
  3. Test the methods via the web interface

JavaScript Bridge API

The webview-bridge.js exposes a single global function:

window.InvokeHostMethod(methodName, ...args): Promise<any>

Parameters:

  • methodName (string): Name of the C# method to call
  • ...args (any[]): Arguments to pass to the method

Returns:

  • Promise<any>: Resolves with the return value, rejects on error

Example:

try {
    const result = await InvokeHostMethod('GetGreeting', 'Bob');
    console.log('Success:', result);
} catch (error) {
    console.error('Failed:', error.message);
}

Build System

The project uses MSBuild to automatically copy web assets:

  • src-web/js/**/* → Output WebFiles/js/
  • WebFiles/ → Output WebFiles/

This ensures all static assets are available in the compiled application.

License

See LICENSE file for details.

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.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
.NET Core netcoreapp2.0 was computed.  netcoreapp2.1 was computed.  netcoreapp2.2 was computed.  netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.0 is compatible.  netstandard2.1 was computed. 
.NET Framework net461 was computed.  net462 was computed.  net463 was computed.  net47 was computed.  net471 was computed.  net472 was computed.  net48 was computed.  net481 was computed. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen40 was computed.  tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
  • .NETStandard 2.0

    • No dependencies.

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
1.1.0 166 5/19/2026
1.0.0 137 5/19/2026