0 solidity web3-donotuse metamask
我想了解智能合约的前端是如何工作的。我正在尝试在我的计算机上运行此代码,但 metamask 始终未定义。您能否详细解释为什么会发生这种情况。为什么它不连接到元掩码提供程序?
<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>
Run Code Online (Sandbox Code Playgroud)
如果您在本地提供 HTML 文件,MetaMask 将无法与您的 DApp 通信。需要一个网络服务器。来自MetaMask 开发人员文档:
由于浏览器安全限制,我们无法与运行在 file:// 上的 dapp 通信。请使用本地服务器进行开发。
另外,请注意MetaMask 的重大更改,它将不再自动注入web3浏览器。相反,用户必须通过接受由window.ethereum.enable(). 请参阅以下代码以在现代 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 !');
}Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2810 次 |
| 最近记录: |