BlazorFrame 2.0.0

There is a newer version of this package available.
See the version list below for details.
dotnet add package BlazorFrame --version 2.0.0
                    
NuGet\Install-Package BlazorFrame -Version 2.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="BlazorFrame" Version="2.0.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="BlazorFrame" Version="2.0.0" />
                    
Directory.Packages.props
<PackageReference Include="BlazorFrame" />
                    
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 BlazorFrame --version 2.0.0
                    
#r "nuget: BlazorFrame, 2.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 BlazorFrame@2.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=BlazorFrame&version=2.0.0
                    
Install as a Cake Addin
#tool nuget:?package=BlazorFrame&version=2.0.0
                    
Install as a Cake Tool

BlazorFrame

A Blazor component that provides an enhanced iframe wrapper with automatic resizing, cross-frame communication, and seamless JavaScript interop with built-in security features.

Features

  • Security-First Design - Origin validation, message filtering, and comprehensive security options
  • Content Security Policy Integration - Built-in CSP helpers for iframe security
  • Responsive - Dynamically resizes iframe based on content height (can be enabled/disabled)
  • Cross-Frame Messaging - Built-in support for postMessage communication with validation
  • Event Callbacks - OnLoad, OnMessage, and security event handling
  • Flexible Styling - Customizable width, height, and additional attributes
  • JavaScript Interop - Seamless integration with Blazor's JS interop
  • Scrolling Control - Enable or disable scrolling within the iframe wrapper
  • Disposal Pattern - Proper cleanup of resources and event listeners

Installation

Install the package via NuGet Package Manager:

dotnet add package BlazorFrame

Or via Package Manager Console:

Install-Package BlazorFrame

Quick Start (Secure by Default)

@using BlazorFrame

<BlazorFrame Src="https://example.com" />

The component automatically derives allowed origins from the Src URL for secure messaging.

Usage Examples

Basic Usage with Event Handling

@using BlazorFrame

<BlazorFrame Src="@iframeUrl"
            Width="100%"
            Height="400px"
            EnableAutoResize="true"
            EnableScroll="false"
            OnLoad="HandleIframeLoad"
            OnValidatedMessage="HandleValidatedMessage"
            OnSecurityViolation="HandleSecurityViolation"
            class="my-custom-iframe" />

@code {
    private string iframeUrl = "https://example.com";

    private Task HandleIframeLoad()
    {
        Console.WriteLine("Iframe loaded successfully!");
        return Task.CompletedTask;
    }

    private Task HandleValidatedMessage(IframeMessage message)
    {
        Console.WriteLine($"Secure message from {message.Origin}: {message.Data}");
        return Task.CompletedTask;
    }

    private Task HandleSecurityViolation(IframeMessage violation)
    {
        Console.WriteLine($"Security violation: {violation.ValidationError}");
        return Task.CompletedTask;
    }
}

Advanced Security Configuration

@using BlazorFrame

<BlazorFrame Src="@iframeUrl"
            AllowedOrigins="@allowedOrigins"
            SecurityOptions="@securityOptions"
            OnValidatedMessage="HandleValidatedMessage"
            OnSecurityViolation="HandleSecurityViolation" />

@code {
    private string iframeUrl = "https://widget.example.com";
    
    private List<string> allowedOrigins = new() 
    { 
        "https://widget.example.com", 
        "https://api.example.com" 
    };
    
    private MessageSecurityOptions securityOptions = new()
    {
        EnableStrictValidation = true,
        MaxMessageSize = 32 * 1024, // 32KB
        LogSecurityViolations = true
    };

    private Task HandleValidatedMessage(IframeMessage message)
    {
        // Handle validated, secure messages
        return Task.CompletedTask;
    }

    private Task HandleSecurityViolation(IframeMessage violation)
    {
        // Log, alert, or take corrective action
        Logger.LogWarning("Security violation: {Error}", violation.ValidationError);
        return Task.CompletedTask;
    }
}

Content Security Policy Integration

@using BlazorFrame

<BlazorFrame Src="@iframeUrl"
            CspOptions="@cspOptions"
            OnCspHeaderGenerated="HandleCspGenerated"
            OnValidatedMessage="HandleValidatedMessage" />

@code {
    private string iframeUrl = "https://widget.example.com";
    
    private CspOptions cspOptions = new CspOptions()
        .AllowSelf()
        .AllowFrameSources("https://widget.example.com", "https://trusted-cdn.com")
        .AllowHttpsFrames()
        .WithCustomDirective("img-src", "'self'", "data:", "https:");

    private Task HandleCspGenerated(CspHeader cspHeader)
    {
        // Apply CSP header to your response
        Console.WriteLine($"Generated CSP: {cspHeader.HeaderValue}");
        
        // In a real application, you might apply this to the HTTP response:
        // HttpContext.Response.Headers.Add(cspHeader.HeaderName, cspHeader.HeaderValue);
        
        return Task.CompletedTask;
    }

    private Task HandleValidatedMessage(IframeMessage message)
    {
        // Handle validated messages
        return Task.CompletedTask;
    }
}

Parameters

Parameter Type Default Description
Src string "" The URL to load in the iframe
Width string "100%" The width of the iframe
CspOptions CspOptions? null Content Security Policy configuration options
Height string "600px" The initial height of the iframe
EnableAutoResize bool true Whether to automatically resize the iframe based on content height
EnableScroll bool false Whether to enable scrolling within the iframe wrapper
AllowedOrigins List<string>? null Explicit list of allowed origins. If null, auto-derives from Src
SecurityOptions MessageSecurityOptions new() Security configuration options
OnCspHeaderGenerated EventCallback<CspHeader> - Callback fired when CSP header is generated
OnLoad EventCallback - Callback fired when the iframe loads
OnMessage EventCallback<string> - Callback fired when receiving valid postMessage (legacy)
OnValidatedMessage EventCallback<IframeMessage> - Callback fired with full message validation details
OnSecurityViolation EventCallback<IframeMessage> - Callback fired when security violations occur
AdditionalAttributes Dictionary<string, object> - Additional HTML attributes to apply

Security Features

Origin Validation

BlazorFrame automatically validates message origins to prevent unauthorized communication:

  • Auto-derived origins: Automatically allows messages from the iframe's source domain
  • Explicit allowlist: Override with custom allowed origins for multi-domain scenarios
  • Protocol enforcement: Ensures HTTPS origins when possible

Message Validation

All incoming messages are validated before reaching your application:

public class MessageSecurityOptions
{
    /// <summary>List of allowed origins (null = auto-derive from Src)</summary>
    public List<string>? AllowedOrigins { get; set; }
    
    /// <summary>Enable strict JSON format validation</summary>
    public bool EnableStrictValidation { get; set; } = true;
    
    /// <summary>Maximum message size (default: 64KB)</summary>
    public int MaxMessageSize { get; set; } = 64 * 1024;
    
    /// <summary>Log security violations</summary>
    public bool LogSecurityViolations { get; set; } = true;
}

Validated Message Model

public class IframeMessage
{
    public required string Origin { get; init; }        // Verified sender origin
    public required string Data { get; init; }          // Validated JSON string
    public bool IsValid { get; init; }                  // Security validation result
    public string? ValidationError { get; init; }       // Error details (if any)
    public string? MessageType { get; init; }           // Extracted message type
}

Content Security Policy (CSP)

BlazorFrame includes comprehensive CSP support to enhance iframe security:

@using BlazorFrame

// Create CSP options with fluent API
var cspOptions = new CspOptions()
    .AllowSelf()
    .AllowFrameSources("https://trusted-domain.com")
    .AllowHttpsFrames()
    .WithScriptNonce("abc123")
    .ForProduction();

// Get CSP header for your HTTP response
var cspHeader = blazorFrame.GetRecommendedCspHeader();
CSP Configuration Examples
// Development environment (relaxed security)
var devCsp = new CspOptions().ForDevelopment();

// Production environment (strict security)
var prodCsp = new CspOptions()
    .ForProduction()
    .AllowFrameSources("https://trusted-widget.com")
    .WithScriptNonce(nonceValue);

// Custom configuration
var customCsp = new CspOptions()
    .AllowSelf()
    .AllowFrameSources("https://widget.example.com", "https://cdn.example.com")
    .AllowDataUrls()
    .WithCustomDirective("img-src", "'self'", "data:", "https:")
    .AsReportOnly("https://csp-report.example.com/report");
CSP Helper Methods
// Generate CSP meta tag for HTML
var metaTag = cspBuilder.BuildCspMetaTag(cspOptions);

// Generate JavaScript to set CSP dynamically
var jsCode = cspBuilder.BuildCspJavaScript(cspOptions);

// Validate CSP configuration
var validation = cspBuilder.ValidateCspOptions(cspOptions);
foreach (var warning in validation.Warnings)
{
    Console.WriteLine($"CSP Warning: {warning}");
}

Security Event Handling

Monitor and respond to security events:

<BlazorFrame OnSecurityViolation="HandleViolation" />

@code {
    private Task HandleViolation(IframeMessage violation)
    {
        // Log, alert, or take corrective action
        Logger.LogWarning("Security violation: {Error}", violation.ValidationError);
        return Task.CompletedTask;
    }
}

Automatic Resizing

BlazorFrame can automatically adjust the iframe height based on the content inside when EnableAutoResize is set to true (default). The component:

  1. Monitors the iframe content document every 500ms
  2. Calculates the maximum height from various document properties
  3. Updates the iframe height dynamically
  4. Handles cross-origin restrictions gracefully
  5. Can be disabled by setting EnableAutoResize="false"

Cross-Frame Communication

Sending Messages from Iframe (Secure)

// Inside your iframe content - specify target origin for security
window.parent.postMessage({ 
    type: 'custom', 
    data: 'Hello from iframe!' 
}, 'https://your-parent-domain.com');

Special Resize Messages

// Send resize messages (validated automatically)
window.parent.postMessage({ 
    type: 'resize', 
    height: 800 
}, 'https://your-parent-domain.com');

Receiving Validated Messages

private Task HandleValidatedMessage(IframeMessage message)
{
    // message.Origin - verified sender origin
    // message.Data - validated JSON string
    // message.MessageType - extracted message type (if present)
    // message.IsValid - always true in this callback
    
    return Task.CompletedTask;
}

Styling and CSS

The component includes built-in CSS styling with wrapper classes:

  • iframe-wrapper - Applied to all iframe wrappers
  • iframe-wrapper scrollable - Applied when EnableScroll="true"

The wrapper provides:

  • 100% width by default
  • Hidden overflow (unless scrollable)
  • Borderless iframe display

Examples

Loading Different Content Types


<BlazorFrame Src="https://docs.microsoft.com" />


<BlazorFrame Src="./local-content.html" />


<BlazorFrame Src="data:text/html,<h1>Hello World!</h1>" />
### Multi-Domain Setup
<BlazorFrame Src="https://widget.example.com"
            AllowedOrigins="@(new List<string> 
            { 
                "https://widget.example.com", 
                "https://api.example.com" 
            })" />

High-Security Configuration with CSP

@using BlazorFrame

<BlazorFrame Src="@secureUrl"
            SecurityOptions="@securityOptions"
            CspOptions="@cspOptions"
            OnSecurityViolation="HandleViolation"
            OnCspHeaderGenerated="HandleCspGenerated" />

@code {
    private string secureUrl = "https://secure-widget.com";
    
    private MessageSecurityOptions securityOptions = new()
    {
        EnableStrictValidation = true,
        MaxMessageSize = 16 * 1024, // 16KB limit
        LogSecurityViolations = true
    };
    
    private CspOptions cspOptions = new CspOptions()
        .ForProduction()
        .AllowFrameSources("https://secure-widget.com")
        .WithScriptNonce("secure-nonce-123")
        .WithCustomDirective("connect-src", "'self'", "https://api.secure-widget.com");
}

Responsive Design

<div class="container-fluid">
    <BlazorFrame Src="@contentUrl"
                Width="100%"
                Height="calc(100vh - 200px)"
                EnableAutoResize="false"
                style="min-height: 400px;" />
</div>

Disabling Auto-Resize for Fixed Height

<BlazorFrame Src="@contentUrl"
            Width="100%"
            Height="500px"
            EnableAutoResize="false"
            EnableScroll="true" />

Custom Styling and Attributes

<BlazorFrame Src="@iframeUrl"
            Width="800px"
            Height="600px"
            EnableAutoResize="false"
            EnableScroll="true"
            class="border rounded shadow"
            style="margin: 20px;"
            sandbox="allow-scripts allow-same-origin" />

Best Practices

  1. Always specify target origin when sending messages from iframe content
  2. Use OnValidatedMessage for new implementations instead of legacy OnMessage
  3. Monitor security violations in production environments
  4. Set appropriate MaxMessageSize based on your use case
  5. Enable logging for security auditing
  6. Use HTTPS for iframe sources when possible
  7. Implement proper error handling for security violations

Requirements

  • .NET 8.0 or later
  • Blazor Server or Blazor WebAssembly

Browser Support

BlazorFrame works in all modern browsers that support:

  • ES6 modules
  • postMessage API with origin validation
  • Blazor JavaScript interop

License

This project is licensed under the MIT License - see the LICENSE file for details.

Support

If you encounter any issues or have questions:

  • Open an issue on GitHub
  • Check existing issues for solutions
  • Suggest new features or improvements
Product Compatible and additional computed target framework versions.
.NET net8.0 is compatible.  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. 
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
2.1.2 92 7/12/2025
2.1.1 91 7/12/2025
2.1.0 88 7/11/2025
2.0.0 121 7/10/2025
1.4.0 116 7/7/2025
1.3.0 116 7/7/2025
1.2.2 120 7/7/2025
1.2.1 119 7/7/2025
1.2.0 120 7/7/2025
1.1.2 125 7/7/2025
1.1.1 118 7/7/2025
1.1.0 74 7/4/2025
1.0.1 83 7/4/2025
1.0.0 103 7/4/2025