[Ethereum] How to get the address via web3


I'm using web3, truffle and testrpc.

In my smart contract, some of the functions can only be called by the owner (or creator) of the contract (i.e. onlyOwner functions). So, I've defined some modifier for that. Also, in the smart contract, I have defined a variable called owner that can be called by anyone to see who the owner is.

I'm designing a UI. I'd like to alert the users, in UI, if they call the onlyOwner functions (e.g. you're not the owner). In my .js file I can call owner.call(); to get the owner address. But I don't know how to get the users address to compare it with the owner address.

Question: How can I get the user's address via web3?

Also, when we switch the default account (i.e. the first account) in MetaMask to 2nd, 3rd, .. account, how the .js file can recognize it and use that account as the default one?

Best Answer

If you are using web(version 0.19.0: latest stable), you can do

1. Download Web3

bower install web3@0.19.0

2. Algo to load Web3, check the connection and retrieve the accounts

    <div id="address"></div>

    <script src="bower_components/web3/dist/web3.min.js"></script>

        window.addEventListener('load', function() {

            // Load WEB3
            // Check wether it's already injected by something else (like Metamask or Parity Chrome plugin)
            if(typeof web3 !== 'undefined') {
                web3 = new Web3(web3.currentProvider);  

            // Or connect to a node
            } else {
                web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));

            // Check the connection
            if(!web3.isConnected()) {
                console.error("Not connected");


            var account = web3.eth.accounts[0];
            var accountInterval = setInterval(function() {
              if (web3.eth.accounts[0] !== account) {
                account = web3.eth.accounts[0];
                document.getElementById("address").innerHTML = account;
            }, 100);



3. Auto-reload after switching account

The solution right now is a basic setInterval function

enter image description here