Calling JavaScript from C# in Blazor WebAssembly (and vice versa) [Blazor JavaScript Interop]

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello everyone and welcome to dot net core central in today's video i am going to cover javascript interrupt for blazer from blazer webassembly we can call javascript function and from javascript functions also we can call c sharp code in blazer webassembly this feature is very important because there are a lot of javascript utility framework out there which does a lot of feature which not necessarily might be available in c sharp so having this feature helps us to use the vast variety of javascript framework out there from the c-sharp code so we would be able to call functions which are deciding on javascript from c-sharp code so to demonstrate this first what i'm going to do is i'm going to create a new javascript file inside of www root so i'm going to go ahead and create a new item and for the file i'm going to select a javascript file and i'm going to name it as main.js once the file is created i'm going to go into index.html and index.html i'm going to add a reference to the javascript file so the reference is added and next thing let's start with a very simple javascript function that we want to call from the c sharp code so there are two types of functions that we can call one is a function without any return which is a void function and another one is with return and in both cases we can either take parameter or we might not take parameter so first let's start with a simple function so for that i am going to create an iffy and if he is an immediate invokable function in javascript so it goes something like this so the function will be immediately invoked and here i'm not going to worry about the namespace collision so i'm just going to because i know for sure i don't have anything else but i'm going to take precaution that if a function already exists i'm not going to overwrite it so i'm just going to do so here i have a very simple function it's a word function it takes a counter value and then just logs the values so it does console.log printing from javascript counter counter that's all very simple doesn't return anything it's a word function so that's the one we are going to try out fast the goal is to print this counter in this javascript function so for that instead of writing code inside of this code behind i'm going to create a new class and i'm going to name it as dotnet to javascript it is not a good name but it's a very clear name at least for this example and now i want to call the function but for calling a javascript function from c sharp we need a particular type which is i js runtime so i'm going to inject the igs from runtime into the constructor of this class and the igs runtime is part of microsoft.js interop namespace i'm going to add it and then i'm going to have a public method which can be invoked by the code behind to call the javascript function so for the public method i'm going to have and i'm going to keep it as void and here what i'm going to do is i'm going to invoke the javascript function so how do i do that i'm going to use i just run time dot i'm going to call the invoke void sync because at this point in time i'm just invoking a void method so i'm going to make a call to invoke word sync and here i'm going to pass the name of the javascript function now given that my javascript function is added to the window itself i can just use log user that's my function name and it takes array of arguments which is passes param so i'm going to pass the counter to it that's all i have to do once i do that from c sharp it is going to invoke the javascript function this particular function and it will do this console.log so it will log into the console of the browser now next thing what i'm going to do is i'm going to go into counter dot razer.cs and here i'm going to add this class as a dependency but for that let me just extract an interface and then instead of the class let's add the interface as a dependency so we can say private so we add the inject attribute which will inject this interface into this class and then here after we print out the counter from the c sharp code we can say dotnet to javascript dot print and here we can pass out the current count and given this is an async method i'm going to add a weight and here i'm going to change it to a sync task so this should do it in the dotnet to javascript we just added the igs runtime and using ijs runtime we are calling invoke void async method where we are passing the function name and the parameter to call the javascript function which is this function here log user and the parameter is a counter and that is going to print it to keep the naming convention i'm just going to rename print test print print sync the last thing that i have to do is in the program i'll have to add the dependency for the new class that i created so i'm going to add scope and it is going to be i dot net to javascript which goes to dotnet to javascript class that's about it and now i'm going to run this application and once the browser shows up i'm going to open up the developer tool so that i can see the console then i'm going to go into the counter and then when i increment the counter you can see it is current count from c sharp and then it is printing in javascript counter one so i am able to and you can see this is coming from the main.js and if i put a breakpoint here and do a click me you can see it is showing up here in the javascript class so that's how you can call a javascript from the c sharp but right now the javascript function that we have it is just calling a function which does not return anything so we can create a function which returns something and that is something we can use from the c sharp so let's do that let's say window dot and this time let's say get formatted message and we're going to do like previously we're going to say this is go to window dot get formatted message or function and this time we will not keep any parameter though you can give the parameter it works same way but i'm not just not going to give any parameter and here we're just going to have a return and we can say hello from javascript to c-sharp this looks like a nice enough message and then what we can do is we can go back to the i dot net javascript and here we can create another function and we can say print formatted message that's about it and then we can go into the class and implement the missing method and here we can do the same thing we can use wait and igs runtime dot and this time instead of invoke void sync we are going to use invoke async and here we are going to pass string because the return type is string and then for the function name we are going to give this get formatted message that's the method and here we can say var message is equal to a weight of get formatted message this has to be a sync and then finally this time let's use the i logger you can say i logger and here we can say logger dot log information and we can just log the message that is coming in so if we do that we have this new function now get formatted message which just returns a string remember this is not doing a console log this is just returning a string and then in the dotnet to javascript we added a new method called print formatted message where we are invoking the function get formatted message and providing the type string for return type by getting the message and then logging the information using i logger and then i'm going to go into counter and here i'm going to call the other method also so i'm going to call it dotnet to javascript dot print formatted message that's it and then i'm going to run this application and just like before i'm going to go to more tools and add the developer tool here so that i can look into the console i'm going to go into counter and now if i click on click me it comes here i'm going to remove this breakpoint go back to console and you can see here current count one printing in javascript counter one and then now it is logging the info that i added and it's saying hello from javascript to c-sharp again current count to printing in javascript counter 2 and the hello from javascript to c sharp so this is working as expected so this shows how we can call javascript functions from c sharp and the function can have a return or it might not have returned it can take parameter or it might not take parameter so this is extremely handy and in my opinion can be really useful in cases where there are functions or frameworks in javascript which are really easily available and can be used from a c sharp code to call back so that's the first part of the video i wanted to cover the next part is calling a c-sharp code from javascript now there are two ways of doing that the first way of calling c-sharp from javascript code is pretty straightforward it is the case where a function is a static function but if you want to call a instance function from javascript that is not very straightforward so first i am going to cover the static function use case so for that what i'm going to do is i'm going to create a new function in the counter dot result.cs itself so i can create a function called private and it has to be static and then task string and let's say help message this is a help message which is coming from configuration or something but for the time being i'm not going to use configuration just going to use hard coded message and i'm going to do a return and here i'm going to say help text from c sharp static function this is the static function and the next thing we're going to do is we're going to use an attribute here which will say js invokable and js invokable is part of microsoft dot interrupt name space so let's do that this is going to make this function the static function available to javascript now one thing to remember is the function name for any static function has to be unique across the solution so if you have a health message here which is js invokable and you provide another help message in another class and give that also js invokable you're going to get an error saying there's a conflict because and why it is so once we call it from here it will become clear because the way it is called is it is called without any type name so now i'm going to do window dot invoke dotnet static function so that's the name of my method and just like before i'm going to do window.invoke or function and here for invoking.net functions there is already a type which is available as a part of the blazer.js and it is called dotnet and we can do dotnet dot invoke method async and here there are a couple of thing goes first thing is the name of the namespace which is blizzard.demo in our case and next thing is the name of the function and the function name is help message i'm just going to give that and then you can give a array of parameters in my case i don't have any so i'm just going to leave it empty and then you can do dot then so it's going to get get a call back and go to data goes to and i'm just going to do console dot log data that's all i have to close this okay now if i run this application we should be getting this help test from c sharps static function should be coming into this method this javascript function and should be printed but for that we want to invoke this function so what i'm going to do is i'm going to go into counter dot razor and i'm just going to create a new button here i'm just going to copy paste this and i'm going to say static method and here what i'm going to do is i'm going to provide the name of the function which is invoke.net static function and this is the name of the javascript function since it is added to the windows i can just use it as is and here it's not going to be at the rate on click anymore because it is a javascript function so it's just going to be on click and it'll be this so that's all i have to do and now let me run this function the reason i got rid of at the red because this is a pure javascript call and not a blazer webassembly on click function now if i open up the developer tool here go to counter and now if i click on this invoke static method i made a mistake here it has to be public so let me run again and once the ui shows up i'm going to open up the developer tool and then we'll go to counter and click on invoke stating method and you can see here help test from c sharp static function has been printed if i go to main.js this is getting called and then in the callback we are logging this text message so this is pretty simple the only thing to keep in mind is the function has to be public static and if it is having a gs invokable you cannot use the same function name anywhere in the class with js invokable attribute because that would create a collision and you cannot do that but otherwise it's pretty straightforward now i'm not 100 sure how useful it is going to be maybe in some complex cases we might need to call c-sharp from javascript but most of the time i think we will be calling javascript from c-sharp now let's look into how do we call an instance method that's a little bit complex first i'm going to create a new class and i'm going to name it as address provider and this class needs to implement i disposable and i'm going to explain why in a few first let's start and let's create a method and let's say public string get address and here i'm just going to return one two three main street and this function we want to make it as js invokable this is the instance function but as i mentioned we cannot call it directly so we have to do some things before so what we have to do so the way it works is we first call a javascript function from here which will register this class or this instance into javascript and then we can use the instance in the javascript to call back any other method which is js invokable in this class so first we have to create a register function so i'm going to create a public async task register and then what i'm going to do is inside of the register function i need to create a reference of this class using dotnet object reference type provided by the framework so for that i'll create private dotnet reference and for dotnet reference the type it is going to create is address provider and i'm going to name it as object reference for the time being and then i also need igs runtime because as i mentioned i have to call the javascript fast to register this object reference in the javascript so that we can call back into the js invokable function of this instance again it's a little bit complex but let's go through it we create a constructor and here i'm going to inject i js runtime and i'm going to initialize this field and then in the register what i'm going to do is i'm going to say object reference is equal to dotnet object reference dot create and in this case we are going to create this this current object that's what we are creating and then now we are going to call evade js runtime dot invoke void sync and here we are going to call a function which is going to register the object reference in the javascript so i don't know the function yet because we have not created it yet so let's go here and create the function so i am going to name it as invoke.net instance function so for that what we can do is we can do window dot invoke dotnet instance function and we can do equal to window dot function or into half function and here this one is going to take the dot net instance as a reference and i'm just going to name it as address provider that's the name of the instance and then here we can use address provider dot invoke method async and here we can provide the name of the method which is get address in this case so get address and then we are going to say dot then and the response comes back we're just going to do console dot log data that's all we are going to do so as you can see register it while registration we pass the instance and then with the instance we can do a callback into the actual instance method so now we can use this function down here as the name of the function we are going to call and then what we can do is now we want to access this but before we do that let me add that into the service registry address provider and next what i'm going to do is i'm going to go to counter dot tracer and here i'm going to create another button and this is going to be invoke instance method and here i'm going to have call instance method this method doesn't exist yet so i should be getting a red squiggly i'm going to go into counter.wizard.cs and here i am going to create this method so i can say private sync task create now the let's quickly should go away and now i need the address here address provider so i can create private address provider address provider get set and i'm going to use the inject attribute to inject this and here i'm going to do away address provider dot register that's about it and one thing i missed in the address provider is that in the dispose i am going to dispose of the object reference object reference dot dispose this needs to be disposed off so i'm just going to dispose it off here now if i run this function and when i click this button what's going to happen is it's going to call this which is going to register call the register the register is going to create the instance using the current instance in the dotnet object reference wrapper and then it is going to call this function to pass the object reference and in the function we are getting it and then we are immediately invoking the instance method here now this is not that useful in a real life scenario once we get the object we're just going to set it to a local variable and then we can use it in a different occasion but i'm just showing this for simplicity at least so that you understand the concept and you understand how it has been used so let me run this now and once the ui is up i am going to open up the developer tool and i'm going to go into counter and this time i'm going to call the invoke instance method and if i call it you can see in the main.js it is coming back here and printing the data which is coming from c sharp instance method which is one two three main street this is the data we send from the address provider this instance method so these are the two very important concept of javascript interop in blazer webassembly one is calling javascript method from c sharp and the other one is calling c sharp method from javascript and that is all i wanted to cover today if you like this video please give me a thumbs up and if you are new to my channel and you think you are getting value out of my channel please subscribe to my channel and thanks so much for watching this video
Info
Channel: DotNet Core Central
Views: 1,463
Rating: 4.8823528 out of 5
Keywords: blazor javascript interop, blazor webassembly javascript interop, calling javascript from c#, blazor call javascript from c#, blazor call c# from javascript, javascript interop blazor, javascript interop blazor webassembly, calling c# from javascript, calling javascript from c# blazor, calling c# from javascript blazor
Id: ozgLMTdocac
Channel Id: undefined
Length: 24min 26sec (1466 seconds)
Published: Sun Dec 13 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.