Is there any way to call from javascript? #135
-
There are some things that I still have to use javascript to solve. and I need to show some alerts from there. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
I've not tried this but you could create a method on the layout component and make it JS invokable. In that you could trigger the toast and then call the method from JavaScript. |
Beta Was this translation helpful? Give feedback.
-
@chrissainty Exactly what I have done and it works pretty nicely. Here is my solution, perhaps it can serve as a template for other users: JavascriptToastBridge.razor @implements IDisposable
@inject IJSRuntime JSRuntime
@inject IToastService ToastService
@code
{
private DotNetObjectReference<JavascriptToastBridge> dotNetObjRef;
private bool disposeCalled;
protected override void OnInitialized()
{
base.OnInitialized();
dotNetObjRef = DotNetObjectReference.Create(this);
}
public async void Dispose()
{
GC.SuppressFinalize(this);
if (!disposeCalled)
{
await JSRuntime.InvokeVoidAsync("JavascriptToastBridge.dispose");
disposeCalled = true;
}
dotNetObjRef?.Dispose();
}
protected override async Task OnAfterRenderAsync(bool firstRender)
{
await base.OnAfterRenderAsync(firstRender);
if (firstRender)
{
await JSRuntime.InvokeVoidAsync("JavascriptToastBridge.afterRender", firstRender, dotNetObjRef);
}
}
[JSInvokable("JavascriptToastBridge.ShowError")]
public async Task ShowError(string message, string heading)
{
await Task.CompletedTask;
ToastService.ShowError(message, heading);
}
} javascript-toast-bridge.js var JavascriptToastBridge = JavascriptToastBridge || {};
JavascriptToastBridge.dotNetObjRef = null;
JavascriptToastBridge.afterRender = (firstRender, dotNetObjRef) => {
JavascriptToastBridge.dotNetObjRef = dotNetObjRef;
}
JavascriptToastBridge.showError = (message, heading) => {
if (JavascriptToastBridge.dotNetObjRef)
JavascriptToastBridge.dotNetObjRef.invokeMethodAsync('JavascriptToastBridge.ShowError', message, heading);
}
JavascriptToastBridge.dispose = () => {
JavascriptToastBridge.dotNetObjRef = null;
} App.razor ...
<JavascriptToastBridge />
... in any JS code ...
JavascriptToastBridge.showError(message, heading);
... |
Beta Was this translation helpful? Give feedback.
@chrissainty Exactly what I have done and it works pretty nicely. Here is my solution, perhaps it can serve as a template for other users:
JavascriptToastBridge.razor