metamask/web3 连接问题

Problems with metamask/web3 connection

我想了解智能合约的前端是如何工作的。 我正在尝试 运行 在我的计算机上使用此代码,但元掩码始终未定义。 你能详细解释一下为什么会这样吗? 为什么它不连接到元掩码提供程序?

        <script>
            $(".sendButton").click(function(){
                let Web3 = require('web3');
                if (typeof web3 !== 'undefined'){
                    web3 = new Web3(web3.currentProvider);
                }
                else {
                    alert('You have to install MetaMask !');
                }
                const abi = some abi
                const contractAddress = "some contract";
                let MyContract = web3.eth.contract(abi);
                let myContractInstance = MyContract.at(contractAddress);
                let functionData = myContractInstance.setMessage.getData($('#inputString').val());
                web3.eth.sendTransaction({
                        to:contractAddress,
                        from:web3.eth.accounts[0],
                        data: functionData,
                    },
                    function(error, response){
                        console.log(response);
                    });
            });
        </script>
    </body>
</html>

如果您在本地提供 HTML 文件,MetaMask 将无法与您的 DApp 通信。需要网络服务器。来自 MetaMask Developer Docs:

Due to browser security restrictions, we can't communicate with dapps running on file://. Please use a local server for development.

此外,请注意 MetaMask breaking change 将不再自动将 web3 注入浏览器。相反,用户必须通过接受 window.ethereum.enable() 创建的提示对话框来授予 DApp 对其帐户的访问权限。请参阅以下代码以在现代 DApp 浏览器和旧版 DApp 浏览器中处理 MetaMask。

// Modern DApp Browsers
if (window.ethereum) {
   web3 = new Web3(window.ethereum);
   try { 
      window.ethereum.enable().then(function() {
          // User has allowed account access to DApp...
      });
   } catch(e) {
      // User has denied account access to DApp...
   }
}
// Legacy DApp Browsers
else if (window.web3) {
    web3 = new Web3(web3.currentProvider);
}
// Non-DApp Browsers
else {
    alert('You have to install MetaMask !');
}