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)
I keep getting the following error :
Could not find 'methods' in 'window'.
**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 file
function print(message){
return "fromJs"+message;
}
window.methods = {
print: function (message) {
return "from js" + message;
}
}
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 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
}
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>
and call it from .Net as follows
await JSRuntime.Current.InvokeAsync<string>("methods.print","mymessage");
// Try this:
// Don't call your class JSInterop
public class MyJSInterop {
public static async Task<string> ChangeText() {
try {
var data = await JSRuntime.Current.InvokeAsync<string>("methods.print","mymessage");
Console.WriteLine($"ReturnedFromJS:{data}");
return data;
} catch (Exception ex) {
return ex.Message;
}
}
}
// Js file
window.methods = {
print: function (message) {
return "from js" + message;
}
};
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