如何使用 web3.js 注销 MetaMask 帐户

Uma*_*jua 21 reactjs ethereum solidity web3js metamask

我正在使用 MetaMask 将交易发送到我的 DApp 中的合约。我需要有关如何在用户单击注销按钮时断开 MetaMask 帐户与我的 DApp 的帮助。

前端:ReactJS

后端:Web3js、Solidity(以太坊)

Ari*_*Ari 14

一旦钱包连接,用户就可以断开连接,您无法控制元掩码。您实际上是通过检查是否可以访问他们的帐户来模拟登录和注销的概念。

const {ethereum} = window;
const accounts = await ethereum.request({method: 'eth_accounts'});
if (accounts && accounts.length > 0) {
    console.log("user is connected");
} else {
    console.log("user not connected");
}
Run Code Online (Sandbox Code Playgroud)

我做的一件事是观察任何帐户更改:

const {ethereum} = window;
const accounts = await ethereum.request({method: 'eth_accounts'});
if (accounts && accounts.length > 0) {
    console.log("user is connected");
} else {
    console.log("user not connected");
}
Run Code Online (Sandbox Code Playgroud)

通常在我的应用程序中,我有一个初始化函数来检查元掩码,它是否已安装?连接了吗?然后我存储状态,以便应用程序可以持续存在,就像用户已登录一样,即使在页面刷新时也是如此。如果发生任何事情,例如帐户更改或断开连接,上述脚本将运行,我会再次运行初始化脚本以重置状态。

window.ethereum.on('accountsChanged', async () => {
    // Do something
});
Run Code Online (Sandbox Code Playgroud)

所以,并没有真正回答你的问题,据我所知,现在有办法联系并断开用户的连接。

// Runs on page load
initialise();

// Runs whenever the user changes account state
window.ethereum.on('accountsChanged', async () => {
    initialise();
});
Run Code Online (Sandbox Code Playgroud)

然后我让我的 UI 对installedconnected变量做出反应。

  • 这是正确的答案,因为目前没有 api 可以要求 metamask 取消关联已连接的帐户。 (2认同)