Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Blazor JS Interop call confusion

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");
}
like image 289
Greg Wacbom Avatar asked Sep 06 '25 03:09

Greg Wacbom


2 Answers

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");
    }
}
like image 85
nAviD Avatar answered Sep 07 '25 21:09

nAviD


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>
like image 29
xcopy Avatar answered Sep 07 '25 20:09

xcopy