The following has two syntax errors of wrong type, however, I can't find any documentation on how this should be used and what I'm doing wrong. What parameters am I suppose to give this open
function?
Syntax error 1 - Argument 2: cannot convert from 'string' to 'System.Threading.CancellationToken'
Syntax error 2 - Argument 3: cannot convert from 'string' to 'object[]'
private async Task HelloWorld()
{
string url = "https://www.google.com";
await JSRuntime.InvokeAsync<object>("open", url, "_blank");
}
JSRuntime
is an abstract class with no static method so you can not call InvokeAsync
method of the class itself. To execute javascript you have to inject an IJSRuntime
object :
public class MyClass{
private readonly IJSRuntime js;
public MyClass(IJSRuntime js){
this.js=js;
}
private async Task HelloWorld()
{
string url = "https://www.google.com";
await js.InvokeAsync<object>("open", url, "_blank");
}
}
It is a bit tricky to tell what is really going on without seeing more of your code, both on the JS side and on the razor side. However, here is a simple example of calling a JS function within your C# code. Btw, I am assuming (hopefully correctly!) that you are doing this within a component, because they code is slightly different for calling this in a class. Also, it would be helpfult to see what, if anything, you are returning from the JS method:
C#
@inject IJSRuntime JSRuntime
@code {
private async Task HelloWorld()
{
string url = "https://www.google.com";
await JSRuntime.InvokeAsync<object>("open", url, "_blank");
}
}
JS
<script>
window.open = function (url, target) {
console.log(url, target)
}
</script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With