1

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;
    },

};
Haytham
  • 834
  • 1
  • 12
  • 31
  • Might be removing parenthesis to function call `setLocalStorage` - `onclick="@setLocalStorage"` will work. – random Jun 16 '19 at 15:37
  • Hi @randomSoul , It doesnt Work , it rasises and error , and it says : cannot convert methdo group to none delegate type "object". – Haytham Jun 16 '19 at 15:48

1 Answers1

2

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");
}
Chris Sainty
  • 7,861
  • 2
  • 37
  • 59