Context
I am trying to understand how and where JsInterop javascript side implemented.
Given the following sample code in my Blazor Server project:
public static ValueTask<string> Prompt(IJSRuntime jsRuntime, string message)
{
// Implemented in exampleJsInterop.js
return jsRuntime.InvokeAsync<string>(
"exampleJsFunctions.showPrompt",
message);
}
and its javascript counterpart:
window.exampleJsFunctions = {
showPrompt: function (message) {
return prompt(message, 'Type anything here');
}
};
(I do understand the SignalR infra and its use for the concept of circuits, I do understand circuits are used for two way client server communication in a Blazor Server project.)
Question
The only client side script what the project uses is: <script src="_framework/blazor.server.js"></script>
As far as understand all javascript execution dispatch functionality should be there.
I supposed the only way to accomplish the javascript call from the server side is some javascript eval() functionality. I tried to locate the source code _framework/blazor.server.js and I suppose it is here here in github, because its build output in the /dist folder contains the file blazor.server.js
I tried to locate this part (where the javascript function given by its name coming from the server is executed) in the typescript sources, with no success. Could anyone point me to the right direction? Am I looking in the wrong place, or there is no eval()?
*** edit: Meanwhile I learned that not only eval() plays here, actually it is the last chance, there is the window["functionName"](arguments);
too, and its variants. Still finding the relevant source lines...
I am trying to understand how and where JsInterop javascript side implemented.
In the app main page, usually _Host.cshtml
(or _index.cshtml or wwwroot/index.html
, etc., depending on your server code structure), somewhere in <head>
or the end of <body>
tag. You can place a <script src="path/to/exampleJsFunctions.js"></script>
there or define functions right away inside a <script>
tag.
FYI, the blazor.server.js
script is the one who is in charge for the websocket connection between the browser and the server. When you call the Prompt(...)
method in the app, server asks the browser (through the websocket) to run a js function called exampleJsFunctions.showPrompt
defined in window
, with the given args message
. If the js function is defined in window
, the browser will run it (and if you put a breakpoint on that using the browser devtools, it will get hit). Otherwise, it will throw an error. There is no eval
.
(Actually, it does not really matters how you define the functions for the browser. The only thing that matters is that when the server asks browser to call the function, the browser can find the function below the window
object.)
If you are so keen to see the source, you should find it in jsinterop sources.