MetaMaskのアカウントのアドレスをブラウザ側で取得します。
下記ファイルはサーバー上で動きます。 ブラウザのセキュリティ上、file://の環境下では動きませんので注意して下さい。
ブラウザを開きMetaMaskにログインした状態で開くと、現在選択しているアカウントのアドレスと、そのETHの金額が表示されます。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <script> window.addEventListener('load', function () { if (typeof web3 !== 'undefined') { console.log('Web3:' + web3.currentProvider.constructor.name); startApp(); }else{ console.log('MetaMaskをインストールして下さい'); } }) function startApp(){ web3.eth.getAccounts(function(error, accounts) { if (error) return; let user_account = accounts[0]; if(typeof user_account !== 'undefined'){ console.log(user_account); getBalance(user_account); }else{ console.log("ログインして下さい"); } }); } //アドレスのETH量を取得 function getBalance(_address){ web3.eth.getBalance(_address, (error, balance) => { if (error) return; console.log(JSON.stringify(balance, null, 2)); }); } </script> </head> <body> </body> </html> |
17行目
非同期による処理が必要でcallbackを記述しています。
関連ページ
MetaMaskのweb3を利用してEtherを送金する[sendTransaction]
参照ページ