Is there a way to add callback to Javascript and get the result in Blazor? Apart from JS Promises.
for example, let say i want to load a file
Javascript Code
window.readFile = function(filePath, callBack) {
var reader = new FileReader();
reader.onload = function (evt) {
callBack(evt.target.result);
};
reader.readAsText(filePath);
}
Can i have something like this in Blazor C#
c#
// read file content and output result to console
void GetFileContent() {
JsRuntime.InvokeAsync<object>("readFile", "file.txt", (string text) => {
Console.Write(text);
});
}
Or Maybe something like this
```c#
// read with javascript
void ReadFileContent() {
JsRuntime.InvokeAsync
// output result callback to console
void resultCallbackMethod(string text) {
Console.Write(text);
}
```#
Thanks
Yes, it is possible. It is covered on the documentation.
In your example, you are trying to send a file. Please be careful to not send something huge, because this communication will happen through SignalR.
@guidevnet Please check my question very well. It is not in the documentation. I wanted a callback
@samtax01 you can pass the instance of the object that you want the javascript to calllback and the method name to call through parameters as workaround. but no there is no support for passing an action to javascript to callback in the moment.
Anything that can be expressed as a callback (that gets called exactly once) can also be expressed as a promise, so I'd recommend wrapping your callback in a promise and returning that.
Thanks for the reply. I will do that