簡體   English   中英

使用 Web3.js 和純 JS 刷新頁面的 MetaMask

[英]MetaMask on page refresh with Web3.js and pure JS

我試圖讓 MetaMask 錢包在頁面刷新時保持連接。 但是,我在萬維網上找不到關於此事的任何信息。 傷心。 另外,據我所知,據說 2019 年有一個 MM 隱私更新,它切斷了注入方法……那么,有沒有辦法用純 JS 原生地做到這一點?

到目前為止的代碼:

const getWeb3 = async () => {
    return new Promise(async (resolve, reject) => {
        const web3 = new Web3(window.ethereum)
        
        try {
            await window.ethereum.request({ method: "eth_requestAccounts" })
            resolve(web3)
        } catch (error) {
            reject(error)
        }
    })
}

document.addEventListener("DOMContentLoaded", () => {
    document.getElementById("connect_button").addEventListener("click", async ({ target }) => {
        const web3 = await getWeb3()
        const walletAddress = await web3.eth.requestAccounts()
        const walletShort = walletAddress.toString()
        const walletBalanceInWei = await web3.eth.getBalance(walletAddress[0])
        const walletBalanceInEth = Math.round(Web3.utils.fromWei(walletBalanceInWei) * 100) / 100
        
        target.setAttribute("hidden", "hidden")
        
        document.getElementById("wallet_balance").innerText = walletBalanceInEth
        document.getElementById("wallet_info").removeAttribute("hidden") 
        document.getElementById("address_shrt").innerText = walletShort.slice(0,3) + '...' + walletShort.slice(-3)
       
    })
})

我對反應一無所知,所以反應指南對我來說有點胡言亂語。 我至少可以遵循任何有用的鏈接或說明嗎? 提前致謝!

您嘗試做的事情在設計上是不可能的。 每次刷新頁面時,您都必須重新請求地址查看權限(出於隱私原因)。

您將在頁面刷新時與這些代碼保持聯系,包括 react、next、next 等。

import { useState, useEffect } from "react";

export default function Home() {
  const [ismetamask, setIsmetamask] = useState(false); // is metamask installed ?
  const [accountaddress, setAccountaddress] = useState([]);

  useEffect(() => {
    if (window) {
      //sometimes window is not loaded, so wait for windows loading
      if (typeof window.ethereum !== "undefined") {
        console.log("MetaMask is installed!");
        setIsmetamask(true);

        // check if metamask is already connected
        if (window.ethereum._state.accounts.length > 0) {
          // metamask is already connected
          ethereum.request({ method: "eth_requestAccounts"});
          setAccountaddress(window.ethereum._state.accounts[0]);
        } else {
          // metamask not connected yet
        }

        // trigger when account change: logout or login
        ethereum.on("accountsChanged", function (accounts) {
        if (window.ethereum._state.accounts.length > 0) {
          setAccountaddress(window.ethereum._state.accounts[0]);
        }else{
          setAccountaddress([]);
        }
        });
      } else {
        console.log("metamask not installed");
      }
    } else {
      console.log("window not loaded yet");
    }
  }, []);

  const signinMetamask = async () => {
    // const accounts =
    await ethereum.request({ method: "eth_requestAccounts" });
    // const account = accounts[0];
  };

  return (
    <>
      {ismetamask ? (
        <>
          {accountaddress.length < 1 ? (
            <>
              <button
                onClick={() => {
                  signinMetamask();
                }}
                className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded"
              >
                Connect Metamask
              </button>
            </>
          ) : (
            <>user: {accountaddress}</>
          )}
        </>
      ) : (
        <>metamask not installed</>
      )}
    </>
  );
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM