如何正确读取表单输入的参数传入MetaMask发起ETH交易
MetaMask 表单转账功能失效问题修复
问题说明
需通过前端表单采集收款地址、ETH转账金额,构造交易参数触发MetaMask转账。当前硬编码参数时转账流程可正常运行,接入表单取数后功能失效;调试时需通过 npx serve 启动本地服务,规避MetaMask对非http环境的访问限制。
核心问题定位
- 输入取值逻辑错误:
<input>元素的用户输入内容存储在value属性中,原代码统一使用innerHTML取值,始终获取到空字符串,无法将用户输入传入交易构造流程 - 冗余无效代码:输入框绑定的
fill_amount、fill_address函数无实际执行逻辑,且事件绑定写法缺失函数调用括号,完全不生效 - 交易参数缺失:构造交易时未明确指定发起地址(
from字段),部分版本的MetaMask无法自动匹配默认账户 - 缺少基础校验:空值、格式非法的地址和金额传入交易逻辑时,会直接导致MetaMask交易弹窗无法唤起
修正后可运行代码
<!DOCTYPE html> <html> <head> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/web3@0.20.7/dist/web3.min.js"></script> </head> <body> <div> <input id="amount" type="number" placeholder="eth" step="0.0001"> <input id="address" placeholder="收款地址"> <button class="pay-button">支付</button> <div id="status"></div> </div> <script type="text/javascript"> window.addEventListener('load', async () => { if (window.ethereum) { window.web3 = new Web3(ethereum); try { await ethereum.enable(); initPayButton() } catch (err) { $('#status').html('用户拒绝了账户访问权限') } } else if (window.web3) { window.web3 = new Web3(web3.currentProvider) initPayButton() } else { $('#status').html('未安装MetaMask(或其他Web3 Provider)') } }) const initPayButton = () => { $('.pay-button').click(() => { // 通过value属性获取表单输入值 const paymentAddress = document.getElementById("address").value.trim() const amountEth = document.getElementById("amount").value.trim() // 基础参数合法性校验 if (!window.web3.isAddress(paymentAddress)) { $('#status').html('收款地址格式非法') return } if (!amountEth || Number(amountEth) <= 0) { $('#status').html('转账金额格式非法') return } web3.eth.sendTransaction({ from: web3.eth.accounts[0], to: paymentAddress, value: web3.toWei(amountEth, 'ether') }, (err, transactionId) => { if (err) { console.log('支付失败', err) $('#status').html('支付失败') } else { console.log('支付成功', transactionId) $('#status').html('支付成功') } }) }) } </script> </body> </html>
调试注意:代码修改完成后,需在项目目录执行
npx serve启动静态服务,通过本地http地址访问页面,禁止直接通过文件协议打开html文件,否则会触发MetaMask的安全拦截。
内容的提问来源于stack exchange,提问作者viritijk
相关产品推荐
相关产品推荐

