Search code examples
.netblazormauimaui-blazor

.NET 9 Maui Blazor Hybrid & Web: Javascript and Reference files


I have been learning .NET 8 Maui Blazor Hybrid for the past few months to build a multiplatform app for Windows, Android, and iPhone. It's pretty cool, but there was a learning curve. I would like to take advantage of version 9.0 so that I can extend my app to the web.

So far, it seems to start working out of the box.

But, I have two questions:

  • Where should I put javascript files?
  • Where and how should I reference... reference files?

Javascript Location I am confused though. Where should I put javascript files? I would have assumed that it would in the .Web project, but there is no wwwroot there. Does it go in the .Shared project? There is a wwwroot, but no index.html to reference the . What about the base project for multiplatform code? There is a wwwroot, and an index.html, but this seems like a strange place to put it.

Reference files My app uses some large files, including an LLM and some audio files. Currently these sit in the References/raw folder in the base project. I would very much like to keep it there because they are the same files.

enter image description here


Solution

  • Where should I put javascript files?

    You can create a new folder in the wwwroot directory, and then create your JavaScript file (e.g., myScript.js) inside this folder.

    In the myScript.js file, define your JavaScript functions:

    function myJsFunction() {
        alert('JavaScript function called from Blazor!');
    }
    

    Where and how should I reference... reference files?

    You can add a reference to the JavaScript file in the wwwroot/index.html file:

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

    Then you can call the JavaScript function from a Blazor component:

    @inject IJSRuntime JS
    
    <button @onclick="CallJsFunction">Call JavaScript Function</button>
    
    @code {
        private async Task CallJsFunction()
        {
            await JS.InvokeVoidAsync("myJsFunction");
        }
    }
    

    You can check this document about Call JavaScript functions from .NET methods in ASP.NET Core Blazor for more information.