Blazor WebAssembly运行时如何将Razor组件变量传递到客户端index.html
结论
这个需求完全可以实现。
注意:你当前写在index.html头中带占位符的script标签会在Blazor应用启动前就被浏览器解析加载,会直接请求无效地址,所以首先要删除这个写死的占位标签,通过动态创建脚本标签的方式实现需求,以下是两种适配不同场景的实现方案:
方案1:Blazor组件初始化后动态加载脚本
适合目标脚本不需要在Blazor启动前使用的场景,实现逻辑最简单:
- 先在index.html中添加辅助JS方法,用于动态创建脚本标签:
<!-- 在index.html的<body>标签末尾添加这段脚本 --> <script> function loadCustomScript(parameter) { const script = document.createElement('script'); script.src = `http://example${parameter}.com`; document.head.appendChild(script); } </script>
- 修改Razor组件代码,通过JS互操作调用上述方法传入接口获取的参数:
@inject IJSRuntime JsRuntime @inject HttpClient client @code { private string data; protected override async Task OnInitializedAsync() { await PassParameter(); } public async Task PassParameter() { // 从接口获取参数值 data = await client.GetFromJsonAsync<string>("api/example"); // 调用JS方法加载对应脚本 await JsRuntime.InvokeVoidAsync("loadCustomScript", data); } }
方案2:Blazor启动前预加载脚本
适合目标脚本需要在Blazor组件中直接使用、必须提前加载的场景:
直接修改index.html的Blazor启动逻辑,关闭自动启动,先请求接口拿到参数,创建脚本加载完成后再启动Blazor:
<!DOCTYPE html> <html> <head> </head> <body> <div id="app">Loading...</div> <!-- 关闭Blazor自动启动 --> <script src="_framework/blazor.webassembly.js" autostart="false"></script> <script> // 先请求接口获取参数 fetch('/api/example') .then(res => res.text()) .then(parameter => { // 创建目标脚本标签 const script = document.createElement('script'); script.src = `http://example${parameter}.com`; // 脚本加载完成后再启动Blazor script.onload = () => Blazor.start(); document.head.appendChild(script); }); </script> </body> </html>
内容的提问来源于stack exchange,提问作者T0bi
相关产品推荐
相关产品推荐

