与 Blazor 进行 JS 互操作时找不到窗口的属性

Ber*_*ian 4 javascript c# interop blazor

您好,我正在尝试jsBlazor. 我的文件结构是这样的:

-root
  -JSInterop.cs
  -js(folder)
    -meth.js  (file containing the js method)
Run Code Online (Sandbox Code Playgroud)

我不断收到以下错误:

 Could not find 'methods' in 'window'.
Run Code Online (Sandbox Code Playgroud)

**调用js的Cs类**

public class JSInterop {
        public static async Task<string> ChangeText() {
            try {
                var data = await JSRuntime.Current.InvokeAsync<string>("./js/meth/methods.print","mymessage");
                Console.WriteLine($"ReturnedFromJS:{data}");
                return data;
            } catch (Exception ex) {

                return ex.Message;
            }

        }
    }
Run Code Online (Sandbox Code Playgroud)

js文件

function print(message){
 return "fromJs"+message;
}

window.methods = {
    print: function (message) {
        return "from js" + message;
    }
}
Run Code Online (Sandbox Code Playgroud)

我已经尝试过只将方法放入window. 我不确定在第一种情况下如何从 js 中的文件中引用方法。

 "[path to file]/[containingfile]/[methodname]" ?
  or i have also tried "[path to file] / window.[methodname]"
Run Code Online (Sandbox Code Playgroud)

无济于事(在第二种情况下)

索引.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width">
    <title>Sms.Studio.Web</title>
    <base href="/" />
    <link href="css/bootstrap/bootstrap.min.css" rel="stylesheet" />
    <link href="css/site.css" rel="stylesheet" />
</head>
<body>
    <app>Loading...</app>

    <!-- browser -->
    <script src="_framework/blazor.webassembly.js"></script>
    <script src="../interop/js/meth.js"></script>

</body>
</html>
Run Code Online (Sandbox Code Playgroud)

uyg*_*ran 6

JSRuntime.Current.InvokeAsync 将相对于全局窗口范围的 js 函数标识符作为其第一个参数。所以在你的 js 文件中你可能有:

window.methods = {
    print: function (message) {
    return "from js" + message
}
Run Code Online (Sandbox Code Playgroud)

在 index.html 中添加您的 js 文件

<script src="css/bootstrap/bootstrap-native.min.js"></script>
<script src="_framework/blazor.webassembly.js"></script>
<script src="js/meth.js"></script>
Run Code Online (Sandbox Code Playgroud)

并从 .Net 调用它如下

await JSRuntime.Current.InvokeAsync<string>("methods.print","mymessage");
Run Code Online (Sandbox Code Playgroud)