I am trying to call a javascript function from my Blazor component using JSinterop but I always get this error :
"Uncaught SyntaxError: Unexpected end of input".
Plus the javascript function is being called automatically when the page is fully laoded which is not the demanded behavior, because i want to trigger the function when a button is clicked.
@page "/jsInterop"
@inject IJSRuntime jsRuntime
<h3>JSinterop</h3>
<button type="button" class="btn btn-primary"
onclick="@setLocalStorage()">
Trigger JavaScript Prompt
</button>
@code{
public object setLocalStorage()
{
return jsRuntime.InvokeAsync<object>("interop.setItem", "username",
"Aymen");
}
}
window.interop = {
setItem: function (name, value) {
window.localStorage[name] = value;
return value;
},
};
You have a syntax error where you have the onclick event
onclick="@setLocalStorage()"
Should be
@onclick=“@setLocalStorage”
All Blazor events now need to be prefixed with an @.
You also need to change the signature of your click handler and you should await the call.
public async Task setLocalStorage()
{
await jsRuntime.InvokeAsync<object>("interop.setItem", "username",
"Aymen");
}