A enhanced secure Blazor iFrame component with built-in origin validation, bidirectional messaging, navigation tracking, and comprehensive security features.
$ dotnet add package BlazorFrameA Blazor component that provides an enhanced iframe wrapper with automatic resizing, cross-frame communication, and seamless JavaScript interop.
Install the package via NuGet Package Manager:
dotnet add package BlazorFrame
Or via Package Manager Console:
Install-Package BlazorFrame
@using BlazorFrame
<BlazorFrame Src="https://example.com" />
@using BlazorFrame
<BlazorFrame Src="@iframeUrl"
Width="100%"
Height="400px"
OnLoad="HandleIframeLoad"
OnMessage="HandleIframeMessage"
class="my-custom-iframe" />
@code {
private string iframeUrl = "https://example.com";
private Task HandleIframeLoad()
{
Console.WriteLine("Iframe loaded successfully!");
return Task.CompletedTask;
}
private Task HandleIframeMessage(string messageJson)
{
Console.WriteLine($"Received message: {messageJson}");
// Parse and handle the message
var message = JsonSerializer.Deserialize<dynamic>(messageJson);
return Task.CompletedTask;
}
}
<BlazorFrame Src="@iframeUrl"
Width="800px"
Height="600px"
class="border rounded shadow"
style="margin: 20px;"
sandbox="allow-scripts allow-same-origin" />
| Parameter | Type | Default | Description |
|---|---|---|---|
Src | string | "" | The URL to load in the iframe |
Width | string | "100%" | The width of the iframe |
Height | string | "600px" | The initial height of the iframe |
OnLoad | EventCallback | - | Callback fired when the iframe loads |
OnMessage | EventCallback<string> | - | Callback fired when receiving postMessage |
AdditionalAttributes | Dictionary<string, object> | - | Additional HTML attributes to apply |
BlazorFrame automatically adjusts the iframe height based on the content inside. The component:
The component supports bidirectional communication through the browser's postMessage API:
Messages sent from the iframe content are automatically captured and forwarded to your OnMessage callback:
// Inside your iframe content
window.parent.postMessage({
type: 'custom',
data: 'Hello from iframe!'
}, '*');Send resize messages from iframe content to manually control height:
// Inside your iframe content
window.parent.postMessage({
type: 'resize',
height: 800
}, '*');BlazorFrame works in all modern browsers that support:
<!-- Web pages -->
<BlazorFrame Src="https://docs.microsoft.com" />
<!-- Local HTML files -->
<BlazorFrame Src="./local-content.html" />
<!-- Data URLs -->
<BlazorFrame Src="data:text/html,<h1>Hello World!</h1>" /><div class="container-fluid">
<BlazorFrame Src="@contentUrl"
Width="100%"
Height="calc(100vh - 200px)"
style="min-height: 400px;" />
</div>Contributions are welcome! Please feel free to submit a Pull Request.
This project is licensed under the MIT License - see the LICENSE file for details.
If you encounter any issues or have questions, please open an issue on GitHub.