簡體   English   中英

如何從 Blazor ZD7EFA19FBE7D3972FD74ZZ 代碼調用 static JavaScript 方法

[英]How to call a static JavaScript method from Blazor C# code

首先,我的JS:

class MyClass {
    static myMethod() {
        alert("TEST");
    }
}

我的 JS 運行時是這樣注入的:

[Inject] protected IJSRuntime Js { get; set; }

我想像這樣調用 static 方法:

Js.InvokeVoidAsync("MyClass.myMethod");

但我收到一個錯誤:

Microsoft.JSInterop.JSException:在“窗口”中找不到“MyClass”。

有沒有一種理智、合理的方法來解決這個問題,或者僅通過將 window.MyClass = MyClass 添加到我的 JS 中?

試試這個(假設服務器端 Blazor)。

在您的 _Host.cshtml 文件中:

(function () {
    window.MyClass = {
        myMethod: function () {
            return alert('TEST');
        }
    };
})();

in.razor 文件(在頂部):

@*Inject JSRuntime to allow JavaScript Interop *@
@inject IJSRuntime JSRuntime

在您的.razor 文件中的方法中:

await JSRuntime.InvokeAsync<string>(
            "MyClass.myMethod", null
            );

請參閱: Blazor JavaScript 互操作

是的,使用 window object 注冊您的方法是正確的。

源代碼的相關部分可以在這里找到:

https://github.com/aspnet/Extensions/tree/master/src/JSInterop

仔細看你會發現:

invokeJSFromDotNet: (identifier: string, argsJson: string) => { ... }

在哪里

@param identifier 標識要調用的全局可訪問的 function。

看一下findJSFunction ,您會看到檢查給定標識符是否已向 window object 注冊的部分,如果沒有,則生成您看到的錯誤:

function findJSFunction(identifier: string): Function {

(...)

    let result: any = window;
    let resultIdentifier = 'window';
    let lastSegmentValue: any;
    identifier.split('.').forEach(segment => {
      if (segment in result) {
        lastSegmentValue = result;
        result = result[segment];
        resultIdentifier += '.' + segment;
      } else {
        throw new Error(`Could not find '${segment}' in '${resultIdentifier}'.`);
      }
    });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM