简体   繁体   中英

How to use Javascript in .NET MAUI Blazor App Hybrid

when ever i try to put javascript link in .NET MAUI Blazor App Hybrid it says "Script tags should not be placed inside components because they cannot be updated dynamically."

Please help

i want to use javascript in .NET MUAI Blazor App Hybrid

You should try to use JavaScript using the modular approach.

Let's assume you have file hello.js which contain functions like below:

export function helloWorld (name) {
    console.log("Hello "+ name);
}

Try creating an interop for your JS file like:

public class Interop : IDisposable
{
    private readonly string _filePath;
    protected readonly IJSRuntime _jsRuntime;
    private Task<IJSObjectReference> _module;
    
    public Interop(IJSRuntime jsRuntime)
    {
        _filePath = filePath;
        _jsRuntime = jsRuntime;
    }
    
   public Task<IJSObjectReference> Module => _module ??= _jsRuntime.InvokeAsync<IJSObjectReference>("import", "./hello.js").AsTask();
    
    //create a method to call function from the JS file
    public async void SayHelloWorld(string name)
    {
        var module = await Module;
        await module.InvokeVoidAsync("helloWorld", name);
    }
    
    public void Dispose()
    {
        if (_module is not null)
        {
            ((IDisposable)_module).Dispose();
        }
    }
}

then use the js function like:

new Interop(JSRuntime).SayHelloWorld("Adam");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM