Learn how to connect wallets and retrieve account information.
Requests user permission and returns connected accounts
Opens a MetaMask popup asking the user to connect their wallet. Only call this in response to user interaction (like a button click). Returns an array of account addresses.
async function connectWallet() {
try {
const accounts = await window.ethereum.request({
method: 'eth_requestAccounts'
});
console.log('Connected account:', accounts[0]);
return accounts[0];
} catch (error) {
console.error('User rejected connection:', error);
}
}Try it:
Returns already-connected accounts (non-interactive)
Returns accounts that are already connected to your site. Unlike eth_requestAccounts, this doesn't show a popup. It returns an empty array if no accounts are connected.
async function checkConnectedAccounts() {
const accounts = await window.ethereum.request({
method: 'eth_accounts'
});
if (accounts.length === 0) {
console.log('No accounts connected');
} else {
console.log('Connected accounts:', accounts);
}
return accounts;
}Key Differences: