在BlazorWebView中注入Javascript



我正在尝试MAUI Blazor,它可能真的很酷,但我遇到了一些问题(很多(。我想调用一些javascript函数到主blazorwebview,但我不知道怎么做。从MainLoyout.razor我采取blazorwebview。

<b:BlazorWebView x:Name="mainView"  HostPage="wwwroot/index.html">
<b:BlazorWebView.RootComponents>
<b:RootComponent Selector="#app" ComponentType="{x:Type local:Main}" />
</b:BlazorWebView.RootComponents>
</b:BlazorWebView>

但从这里开始,我不知道如何注入javascript。感谢

请查看以下文档:https://learn.microsoft.com/en-us/aspnet/core/blazor/javascript-interoperability/call-dotnet-from-javascript?view=aspnetcore-6.0

主页.xaml

<Button Text="Press me" Clicked="button_Clicked"/>
<b:BlazorWebView HostPage="wwwroot/index.html"></b:BlazorWebView>

主页.xaml.cs

private async void button_Clicked(object sender, EventArgs e)
{
var js = webView.Handler.MauiContext.Services.GetService<IJSRuntime>();
var result = await js.InvokeAsync<string>("executeMe", "DEF");
// Look at the Visual Studio Output window to see this message
Debug.WriteLine(result);
}

MauiProgram.cs

public static class MauiProgram
{
public static MauiApp CreateMauiApp()
{
var builder = MauiApp.CreateBuilder();
builder
.UseMauiApp<App>()
.ConfigureFonts(fonts =>
{
fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
});
builder.Services.AddMauiBlazorWebView();
builder.Services.AddBlazorWebViewDeveloperTools();
return builder.Build();
}
[JSInvokable]
public static async Task<string> CallMeFromJs(string a)
{
return a + " OK!";
}
}

index.html

<input type="button" id="btn" value="Call .Net" />
<script type="text/javascript">
window.executeMe = (a) => {
// Click on BlazorWebView and press F12 to open DevTools to see the console logs
// You might need to add builder.Services.AddBlazorWebViewDeveloperTools(); in the CreateMauiApp() method
console.log("Call: " + a);
return a + " OK!";
};
</script>
<script type="text/javascript">
document.getElementById('btn').onclick = function () {
DotNet.invokeMethodAsync('MauiApp1', 'CallMeFromJs', 'ABC')
.then(data => {
// Click on BlazorWebView and press F12 to open DevTools to see the console logs
// You might need to add builder.Services.AddBlazorWebViewDeveloperTools(); in the CreateMauiApp() method
console.log(data);
});
};
</script>
<script src="_framework/blazor.webview.js" autostart="false"></script>

我希望它能有所帮助。

最新更新