Reputation: 57
I'm trying to do some alchemy here: I have a Blazor Wasm application that I try (for some reasons) to encapsulate into an HTML Custom Element.
So far I understood that the script _framework/blazor.webassembly.js
is the bootstrap of the application.
However, if I put that script into the shadow root of my HTML Custom Element, the script seems executed, breakpoints are reached, but nothing related to the Blazor application happens: the dotnet.wasm
is not loaded, no message, no error is shown.
So the question is: did someone tried to encapsulate a Blazor Wasm application into an HTML Custom Element? How can it be done, if it can?
Edit:
Here is the resulting DOM that I have so far:
<html lang="en">
<head>
<!-- Usual things omitted -->
</head>
<body>
<my-custom-element>
#shadowRoot
<div id="app"></div>
<script src="_framework/blazor.webassembly.js" type="text/javascript"></script>
</my-custom-element>
<!-- The shadowRoot and its content is generated by the custom element declared in this script -->
<script src="importMyCustomElement.js" type="text/javascript"></script>
</body>
</html>
Upvotes: 1
Views: 2375
Reputation: 136
A bit late, but currently this is now possible. Blazor now supports registering components that can be instantiated by Javascript. There's also experimental support for registering them as custom elements.
Here's the recent devblog for it https://devblogs.microsoft.com/aspnet/asp-net-core-updates-in-net-6-rc-1/#blazor-custom-elements
You can get started by installing the pre-release nuget package
Microsoft.AspNetCore.Components.CustomElements
Then instead of adding a root component, you can do this instead.
// WASM sample
builder.RootComponents.RegisterAsCustomElement<Counter>("my-blazor-counter");
// Server-side sample
builder.Services.AddServerSideBlazor(options =>
{
options.RootComponents.RegisterAsCustomElement<Counter>("my-blazor-counter");
});
Add the following scripts on your index
<script src="_content/Microsoft.AspNetCore.Components.CustomElements/BlazorCustomElements.js"></script>
<script src="_framework/blazor.webassembly.js"></script>
With that you can now use those components as custom elements, which can be used either in another SPA framework or just plain html.
// Plain usage
<my-blazor-counter increment="1"></my-blazor-counter>
// React
let count = 1;
<my-blazor-counter increment={count}></my-blazor-counter>
This works in both server-side, and webassembly. It can also be a neat way of creating real-time web-components (e.g chat box) using Server side Blazor without having to deal with SignalR.
Upvotes: 3
Reputation: 13
I am investigating this as well. Looks like you are missing <div id="app">
element. Notice the id="app" this is what Blazor looks for by default (see Program.cs of Blazor Webassembly app).
Upvotes: 0