Reputation: 21
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:
stating that I am trying to access the 0 index of an undefined object (most probably accounts).
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.
Upvotes: 0
Views: 120