blazorblazor-server-side

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


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


Solution

  • Firstly you could try add reference without ~

    <script src="/js/custom.js"></script>
    

    Secondly, you may need to rebuild the solution to make new scripts work.
    enter image description here