Quantcast
Channel: Active questions tagged blazor - Stack Overflow
Viewing all articles
Browse latest Browse all 4839

Why can't Blazor see the JS function in a separate file?

$
0
0

I have created a new .js file and connected it to App.razor. But I got issue when tried to call a function in this file:

[2024-08-19T16:59:42.406Z] Error: Microsoft.JSInterop.JSException: Could not find 'getMessage' ('getMessage' was undefined).Error: Could not find 'getMessage' ('getMessage' was undefined).    at https://localhost:7151/_framework/blazor.web.js:1:734    at Array.forEach (<anonymous>)    at l.findFunction (https://localhost:7151/_framework/blazor.web.js:1:702)    at b (https://localhost:7151/_framework/blazor.web.js:1:5445)    at https://localhost:7151/_framework/blazor.web.js:1:3238    at new Promise (<anonymous>)    at y.beginInvokeJSFromDotNet (https://localhost:7151/_framework/blazor.web.js:1:3201)    at gn._invokeClientMethod (https://localhost:7151/_framework/blazor.web.js:1:62841)    at gn._processIncomingData (https://localhost:7151/_framework/blazor.web.js:1:60316)    at connection.onreceive (https://localhost:7151/_framework/blazor.web.js:1:53957)   at Microsoft.JSInterop.JSRuntime.InvokeAsync[TValue](Int64 targetInstanceId, String identifier, Object[] args)   at BlazorApplication.Server.Components.ThemeButton.ChangeTheme()   at Microsoft.AspNetCore.Components.ComponentBase.CallStateHasChangedOnAsyncCompletion(Task task)   at Microsoft.AspNetCore.Components.RenderTree.Renderer.GetErrorHandledTask(Task taskToHandle, ComponentState owningComponentState)

But if I will define it right in App.razor in this way everything will be fine.

<body><Routes @rendermode="InteractiveServer" /><script>         window.getMessage = () => {             return "Hello, World!";         };</script> // Works<script src="~/js/custom.js"></script> // Not works, but contains the same function<script src="~/js/bootstrap.bundle.min.js"></script><script src="_framework/blazor.web.js"></script></body>

The component, where I am using JS interop:

@inject IJSRuntime JS<button class="btn btn-outline-primary" @onclick="ChangeTheme">Change theme</button><br /><span>Message: @Text</span>@code {    private string Text = "";    private async Task ChangeTheme()    {        Text = await JS.InvokeAsync<string>("window.getMessage");    }}

I did find similar issues and solutions to them, but nothing fixed this one.

I've already tried those solutions:

Blazor Component Javascript Errors (Microsoft.JSInterop.JSException)

Could not find property of window when doing JS interop with Blazor


Viewing all articles
Browse latest Browse all 4839

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>