浏览器检测
验证浏览器是否正在运行MetAmask
if (typeof window.ethereum !== 'undefined') { console.log('MetaMask is installed!'); }
MetaMask检测
与其他浏览器兼容,检测是否是使用metaMask
ethereum.isMetaMask
用户状态
当前网络
ethereum.networkVersion
当前账户
ethereum.selectedAddress
连接MetaMask
官方建议是不要在页面加载的时候请求,尽量是使用按钮点击连接方式,连接请求挂起的时候禁用按钮。
点击按钮连接dapp
ethereum.request({ method: 'eth_requestAccounts' });
示例
<button class="enableEthereumButton">Enable Ethereum</button> <h2>Account: <span class="showAccount"></span></h2>
const ethereumButton = document.querySelector('.enableEthereumButton'); const showAccount = document.querySelector('.showAccount'); ethereumButton.addEventListener('click', () => { getAccount(); }); async function getAccount() { const accounts = await ethereum.request({ method: 'eth_requestAccounts' }); const account = accounts[0]; showAccount.innerHTML = account; }
遇到钱包多账户切换的时候,需要使用监听事件
ethereum.on('accountsChanged', (accounts) => { // Handle the new accounts, or lack thereof. // "accounts" will always be an array, but it can be empty. console.log(accounts,"accountsChanged") });
网络也需要监听,需要保证dapp使用的链正确
ethereum.on('chainChanged', (chainId) => { // Handle the new chain. // Correctly handling chain changes can be complicated. // We recommend reloading the page unless you have good reason not to. window.location.reload(); });
chainid network
Hex | Decimal | Network |
0x1 | 1 | Ethereum Main Network (Mainnet) |
0x3 | 3 | Ropsten Test Network |
0x4 | 4 | Rinkeby Test Network |
0x5 | 5 | Goerli Test Network |
0x2a | 42 | Kovan Test Network |
0x80 | 128 | heco mainnet network |
0x100 | 256 | heco testnet network |