Saucter
Saucter

Reputation: 79

Trying to invoke a JS function from C# (Blazor) but it states that the function could not be found

Basically, I'm trying to invoke a basic custom JS function from C# (for learning purposes) and whenever I try to run that function it says that it could not be found even though I have added the .js file containing the function to the Index.html file as a script

The .js file

function my_function(message)
{
    console.log("Message: "+message)
}

The index.html file's body

<body>
    <div id="app">Loading...</div>

    <div id="blazor-error-ui">
        An unhandled error has occurred.
        <a href="" class="reload">Reload</a>
        <a class="dismiss">🗙</a>
    </div>
    <script src="_framework/blazor.webassembly.js"></script>
    <script src="JS/example.js"></script>
</body>

The file trying to invoke the function

@code
{
    public async Task myMethod()
    {
        await js.InvokeVoidAsync("my_function", "Custom message");
    }
}

I checked the file's name, it's exactly as written, even html prompts to write the name, it's the exact same one. The applications runs, but whenever I try to access the part that uses the method, I get a long error with the main part of being this:

Could not find 'my_function' ('my_function' was undefined)

Any help would be extremely appreciated, and if anyone has seen my previous posts, ik that I'm probably asking way too much but I genuinely tried everything I could find, but nothing worked

Upvotes: 0

Views: 1043

Answers (1)

Marvin Klein
Marvin Klein

Reputation: 1756

You'll need define your function as a JavaScript property like this:

window.my_function = (message) => {
     console.log("Message: " + message);
};

Then you can call it with the IJSRuntime like this:

await js.InvokeVoidAsync("my_function", "Custom message");

Upvotes: 3

Related Questions