1. Inject JSRuntime in the component page.
2. JSRuntime instance has a method named InvokeAsync using which you can invoke JS functions. JSRuntime will search the given method in the window object, hence place your function in the window object. I have placed my function in jsexample.js file.
3. We need to place the client resources in the wwwroot folder and hence place the jsexample.js file in the wwwroot folder and refer it in the _Host.cshtml file.
The following shows the result of the above invoke operation.
Now I have refactored the previously used function as below to handle return value from the JS function.
Now the result will be as follows.
- The method should be static
Syntax: DotNet.invokeMethodAsync(APPLICATION_NAME, FUNCTION_NAME, [ARGS,...]); Example: DotNet.invokeMethodAsync("BlazorKeyApp", "invokeFromJs", "Hello World");
The output will be as follows.
It is also possible to call a class method and to do so we need to send the class instance to the client side by wrapping it using DotNetObjectRef.Create method and invoke the appropriate method using invokeMethodAsync method of that particular DotNet class instance.
To explain this, I have created the below Helper class and going to invoke the MyMethod from this instance using JsInterop. Here the MyMethod must be decorated with JsInvokable attribute.
And in the button click, I am sending the class instance reference to the client side as follows.
The following shows the output of the above explained operation.
Handling return value from C# method
The invokeMethodAsync will return a Promise object, you can get the return value by simply adding then function handler as follows.
DotNet.invokeMethodAsync( "BlazorKeyApp", "invokeFromJs", "Hello World").then((data) => console.log(data))
You can perform error handling by adding catch function to the same method.
I hope that this post have given you some idea about Blazor JS Interop concept. You can use the JS Interop to leverage the web features that cannot be achieved, at least for now.
I would recommend to avoid the below things while using JS interop.
- Don`t send Large data through JS Interop as it would cause buffer side exceeded exception.
- Don`t send DOM elements through JS Interop.
- Try to reduce the number of calls using JS Interop.
Also I would say that adhering to the JS Interop completely is a bad idea as it would results in stability issues and performance.
If you find this article interesting, follow me on Twitter for more..