I am trying to run javascript code through C#. I am using JSInterop to call javascript function from C#. I have installed metammask sdk and then trying to get the account after connecting.
window.getAccount = async function () {
try {
const accounts = await provider.request({ method: "eth_requestAccounts" });
console.log("accounts = ", accounts);
if (accounts.length != 0 || accounts != undefined) {
console.log("accounts = ", accounts);
console.log("account[0] = ", accounts[0]);
return accounts[0]; // Return the first account
}
else
return "new error"
} catch (err) {
if (err.code === 4001) {
console.log("Please connect to MetaMask.");
return "Allow to connect to Metamask"; // Return a message indicating to connect to MetaMask
} else {
console.error(err);
throw err; // Re-throw the error
return " error ..."
}
}
}
The above is my javascript code. Here i am returning the account if the user accepts the connecting request and returning a message if he rejects.
I am calling this function from the cs file like
string output = await JsRuntime.InvokeAsync<string>("getAccount");
Console.WriteLine("output = ", output);
The issue:
- When I am rejecting the connection request the message “Please connect to metamask” gets consoled but after that an error occurs : crit: Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100]
Unhandled exception rendering component: Cannot read properties of undefined (reading ‘0’)
TypeError: Cannot read properties of undefined (reading ‘0’)
at window.getAccount (https://localhost:57476/js/index.bundle.js:1:483)
Microsoft.JSInterop.JSException: Cannot read properties of undefined (reading ‘0’)
TypeError: Cannot read properties of undefined (reading ‘0’)
at window.getAccount (https://localhost:57476/js/index.bundle.js:1:483)
at Microsoft.JSInterop.JSRuntime.d__16`1[[System.String, System.Private.CoreLib,
stating that I am trying to access the 0 index of an undefined object (most probably accounts).
- When I am accepting the request then nothing/empty string is returned.
I tried changing the structure of the getAccount funtion hoping the return statement miht work, but no progress.
Expected result: The account should be returned if the user accepts the connect request and if the user rejects the connect the error message should be returned.


