我正在尝试使用 JS Interop 从 C# 调用 JS 函数。我定义了两个方法,然后使用 InvokeVoidAsync 进行调用。
问题是在像edge和firefox这样的浏览器中,会出现错误,指出该函数未定义(未定义),但在chrome中它很好并且可以工作,而有时在chrome中,其中一个函数会返回错误未定义。
window.getAccount = async function () {
try {
if (provider === null) {
return { "Success": false, "Address": null, "Message": "Metamask not detected" };
}
else {
const accounts = await provider.request({ method: "eth_requestAccounts" });
console.log("connected accounts = ", accounts);
if (accounts.length !== 0 || accounts !== undefined) {
return { "Success": true, "Message": null, "Address": accounts[0].toString() };
}
else
return "new error";
}
} catch (err) {
if (err.code === 4001) {
/* console.log("Please connect to MetaMask.");*/
return { "Success": false, "Address": null, "Message": "Allow to connect to Metamask" }; // Return a message indicating to connect to MetaMask
} else {
console.error(err);
console.log(err);
//throw err; // Re-throw the error
return { "Success": false, "Address": null, "Message": err.toString() };
}
}
}
第二个功能
window.getChainId = async function () {
return chainId.toString();
}
我在 C# 中调用这些函数,例如 -
ConnectWallet connectResponse = await JsRuntime.InvokeAsync<ConnectWallet>("getAccount");
和
string chainId = await JsRuntime.InvokeAsync<string>("getChainId");
有什么建议可以正确地做到这一点吗?
您可以尝试编写如下部分的函数
async function getAccount() {
...
async function getChainId() {
...