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

};
2
  • Might be removing parenthesis to function call setLocalStorage - onclick="@setLocalStorage" will work. Commented Jun 16, 2019 at 15:37
  • Hi @randomSoul , It doesnt Work , it rasises and error , and it says : cannot convert methdo group to none delegate type "object". Commented Jun 16, 2019 at 15:48

1 Answer 1

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");
}
Sign up to request clarification or add additional context in comments.

1 Comment

You forgot to add the "async" keyword in order to use "await " @Chris Sainty

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.