简体   繁体   中英

Show wallet address after connecting Metamask with Web3.js

I got this code off github which allows you to connect to MetaMask using web3.js and also to make payment. I then modified it to

  1. Display a Connect Button when user is not logged in by checking if the content of an element is empty and if it is not empty, the connect button is hidden.
  2. Retrieve the connected wallet address which is in the element that hides the button.

I want the connected wallet to show up and hide the Connect button as soon as MetaMask is connected but it does not do that until i manually reload the page

Below is my code

  <head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
   <script src="https://unpkg.com/@metamask/legacy-web3@latest/dist/metamask.web3.min.js"></script>
  </head>
  <body>
    <div>
        
      <div id="selected-account"></div>
      <button class="pay-button">Pay</button>
      <div id="status"></div>
      <div id="accTabs"></div>
    </div>
    <script type="text/javascript">
      async function initWeb3() {
        if (window.ethereum) {
        window.web3 = new Web3(ethereum);
        
        try {
            
          await ethereum.enable();
    window.location.reload();
          } catch (err) {
            $("#status").html("User denied account access", err);
          }
        } else if (window.web3) {
            
          return (window.web3 = new Web3(web3.currentProvider));
          
        } else {
          return $("#status").html("No Metamask (or other Web3 Provider) installed");
        }
      }
      
      selectedAccount = ethereum.selectedAddress;
  document.querySelector("#selected-account").textContent = selectedAccount;

      $(".pay-button").click(async () => {
        await initWeb3();
        // paymentAddress is where funds will be send to
        const paymentAddress = "0x192c96bfee59158441f26101b2db1af3b07feb40";
        const amountEth = "1";



        web3.eth.sendTransaction(
          {
            to: paymentAddress, 
          value: web3.toWei(amountEth, 'ether')
          },
          (err, transactionId) => {
            if (err) {
              console.log("Payment failed", err);
              $("#status").html("Payment failed");
            } else {
              console.log("Payment successful", transactionId);
              $("#status").html("Payment successful");
            }
          }
        );
      });
    </script>
    
    <script>
  if ($('#selected-account').text() == '') {
document.getElementById("accTabs").innerHTML = '<button onclick="initWeb3()">Connect Ethereum</button>';
} else {


}
     
</script>
  </body>
</html> 

Your help will be appreciated!

Thanks for your assistance.

you should use onload function like this window.onload = async function () { when it works you need to verify if window have ethereum if everything is ok then connect to a provider using new Web3.providers.HttpProvider

 window.onload = async function () {
        const detectMM = () => typeof window.ethereum !== "undefined";

        if (detectMM) {
          document.getElementById("enableMM").getAttribute("disabled", false);

          try {
            const provider = new Web3.providers.HttpProvider(
              "HTTP://127.0.0.1:7545"
            );
            web3 = new Web3(window.ethereum);
            web3Host = new Web3(provider);

            await connect();

            await web3.eth.net
              .isListening()
              .then(
                () =>
                  (document.getElementById(
                    "network"
                  ).innerHTML = `available network`)
              )
              .catch(
                (e) =>
                  (document.getElementById(
                    "network"
                  ).innerHTML = `Something went wrong: ${e}`)
              );
          } catch (error) {
            alert(error);
          }
        } else {
          document.getElementById("enableMM").getAttribute("disabled", true);
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM