Home > database >  Inject javascript body in blazor wasm dynamically
Inject javascript body in blazor wasm dynamically

Time:10-20

All the methods I have seen in blazor wasm to inject Javascript involves calling a javascript function. what if I want to inject a dynamic javascript function block. Example: await JS.InvokeVoidAsync("<script>alert('A')</script",null); Is this possible? "InvokeAsync" only seems to accept a function name.

CodePudding user response:

Try it like this call the function name and then pass the data as an argument, as you're directly invoking JS, the script tag is unnecessary

await JSRuntime.InvokeVoidAsync("alert", "Hello!");

CodePudding user response:

Add the following function in index.html

 <script>
        window.addCode = (code) => {
            var JS = document.createElement('script');
            JS.text = code;
            document.body.appendChild(JS);
        };        
    </script>

call it from razor page: await JS.InvokeAsync<object>("addCode","alert('A')")

  • Related