web3 js 连接 metamask 获取账户信息 web3.eth.getAccounts 为空

叶淇
2023-12-01

web3.eth.getAccounts获取账号地址为空解决办法

这里用到 web3js 1.3.5 版本了,如果版本是新版,可以用下面的方法连接。

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8" />
	<meta name="renderer" content="webkit"/>
	<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
	<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"/>
</head>
<body>
	<button id="btn-wallet" onclick="linkWallet()">连接wallet</button>
	<button onclick="getAccount()">获取account</button>
	<input id="input-account" readonly="readonly" type="text" value="" />
</body>
<script src="https://cdn.jsdelivr.net/npm/web3@latest/dist/web3.min.js" type="text/javascript" charset="utf-8">
</script>
<script type="text/javascript">
	var web3Provider;
	var web3js;
	
	function linkWallet() {
		if (ethereum) {
			web3Provider = ethereum;
			// 新版需要请求用户授权
			try {
				ethereum.enable();
			} catch (error) {
				alert("用户取消授权");
				return;
			}
		} else if (web3) {
			// MetaMask Legacy dapp browsers...
			web3Provider = web3.currentProvider;
			console.log("web3.currentProvider:");
			console.log(web3.currentProvider);
		} else {
			web3Provider = new Web3.providers.HttpProvider('http://localhost:8545');
			console.log("https://http-testnet.hecochain.com");
		}
		web3js = new Web3(web3Provider);
		
		document.getElementById("btn-wallet").innerText = "重新连接";
	}
	
	function getAccount() {
		if (!web3js) {
			document.getElementById("input-account").value = "请先连接 wallet";
			return;
		}
		web3js.eth.getAccounts(function(error, result) {
			if (!error) {
				document.getElementById("input-account").value = result;
			} else {
				document.getElementById("input-account").value = "获取地址失败";
			}
		});
	}
</script>
</html>

参考网站:

http://www.fengyunxiao.cn/

 类似资料: