blazorblazor-server-sideblazor-webassembly

How to use javascript code behind for blazor component


I'm trying to use JavaScript code behind in blazor here is my solution files in rider rider solution file

and inside TestComponent.razor.js there is code by default, I don't know what is this (is this necessary ?)

    export class TestComponent {
      
    }
    
    window.TestComponent = TestComponent;

and this is my js code trying to put into TestComponent.razor.js file

example: we have two function and 1 line JS code without putting into any function , so how to put these js code into TestComponent.razor.js and how to use them


    console.log("no function code");
    
    function MyLogFunction(){
        console.log("function1")
    }
    

Solution

  • Here's some code that demonstrates how to set up the js file and load it from the component.

    Note that this code is quoted almost verbatim from the MS document article load-a-script-from-an-external-javascript-file-js-collocated-with-a-component

    Home.razor.js

    export function showPrompt2(message) {
        return prompt(message, 'Type your name here');
    }
    

    Home.razor

    @page "/"
    @inject IJSRuntime Js
    @implements IAsyncDisposable
    
    <PageTitle>Home</PageTitle>
    
    <h1>Hello, world!</h1>
    
    <div class="mb-3">
        <button class="btn btn-primary" @onclick="this.OnButtonClick">Click</button>
    </div>
    
    <div class="bg-dark text-white m-2 p-2">
        <pre>@result</pre>
    </div>
    
    @code {
        private IJSObjectReference? module;
        private string? result;
    
        private async Task OnButtonClick()
        {
            if (module is not null)
                result = await module.InvokeAsync<string>("Window.Home.showPrompt2", "What's your name?");
        }
    
        // Registers the module whwn the component first renders
        protected async override Task OnAfterRenderAsync(bool firstRender)
        {
            if (firstRender)
                module = await Js.InvokeAsync<IJSObjectReference>("import", "./Components/Pages/Home.razor.js");
        }
    
        // Need to dispose the IJSObjectReference when the component goes out of scope
        async ValueTask IAsyncDisposable.DisposeAsync()
        {
            if (module is not null)
                await module.DisposeAsync();
        }
    }