与Blazor进行JS互操作时找不到窗口的属性 [英] Could not find property of window when doing JS interop with Blazor
问题描述
您好,我正在尝试从 js
文件中调用方法.我的文件结构是这样的:
Hello i am trying to call a method from a js
file from Blazor
.
My file structure is like this:
-root
-JSInterop.cs
-js(folder)
-meth.js (file containing the js method)
我不断收到以下错误:
Could not find 'methods' in 'window'.
**调用js的CS类**
**Cs class that calls the js **
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;
}
}
}
Js文件
function print(message){
return "fromJs"+message;
}
window.methods = {
print: function (message) {
return "from js" + message;
}
}
我已经尝试过将方法仅放在属性中并将其作为属性放在 window
中.我不确定在第一种情况下如何从js文件中引用方法.
I have tried both putting just the method and putting it as a property in the window
.I am not sure in the first case how do you refer a method from a file in js.
"[path to file]/[containingfile]/[methodname]" ?
or i have also tried "[path to file] / window.[methodname]"
无济于事(在第二种情况下)
to no avail (in the second case)
Index.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>
推荐答案
JSRuntime.Current.InvokeAsync将相对于全局 window 范围的js函数标识符作为其第一个参数.因此,在您的js文件中,您可能有:
JSRuntime.Current.InvokeAsync takes a js function identifier relative to the global window scope as its first argument. So in your js file you may have :
window.methods = {
print: function (message) {
return "from js" + message
}
将您的js文件添加到index.html
Add your js file in index.html
<script src="css/bootstrap/bootstrap-native.min.js"></script>
<script src="_framework/blazor.webassembly.js"></script>
<script src="js/meth.js"></script>
并按如下方式从.Net调用
and call it from .Net as follows
await JSRuntime.Current.InvokeAsync<string>("methods.print","mymessage");
这篇关于与Blazor进行JS互操作时找不到窗口的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!