![](/img/trans.png)
[英]How to detect an account change in MetaMask using Meteor and web3?
[英]Better pattern to detect web3 default account when using metamask
上下文:我想使用 blockies 在页面上呈现一个身份图标,我从 web3 获取 defaultAccount,为此,用户必须使用钱包中选择的地址登录到 metamask。
问题:web 应用程序似乎没有在页面的加载事件上检测到 web3 对象,建议在 wchih 进行检测。
代码:下面的灵感来自以下建议:
https://github.com/MetaMask/metamask-plugin/issues/1158
我一直有间歇性行为,有时 web3 存在,有时不存在,我能想到的唯一解决方案是有一个计时器,但这在我看来有点过于简单,我更喜欢更优雅的东西。
问题:是否有更好的解决方案来在页面加载时从 web3 中检测 defaultAccount?
function startApp() {
GenerateIdenticon();
}
window.addEventListener('load', function () {
// Checking if Web3 has been injected by the browser (Mist/MetaMask)
if (typeof web3 !== 'undefined') {
// Use Mist/MetaMask's provider
window.web3 = new Web3(web3.currentProvider);
if (web3.currentProvider.isMetaMask === true) {
if (typeof web3.eth.defaultAccount === 'undefined') {
document.body.innerHTML = '<body><h1>Oops! Your browser does not support Ethereum Ðapps.</h1></body>';
}
else {
startApp();
}
}
else {
alert('No web3? Please use google chrome and metamask plugin to enter this Dapp!', null, null);
// fallback - use your fallback strategy (local node / hosted node + in-dapp id mgmt / fail)
window.web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
}
function _Connect(callback){
if(typeof web3 !== 'undefined') {
web3 = new Web3(window.web3.currentProvider);
web3.version.getNetwork((err, netId) => {
switch (netId) {
case "1":
callback('Switch Network', null);
break
case "2":
console.log('This is the deprecated Morden test network.');
callback('Switch Network', null);
break
case "3":
console.log('Connected to the ropsten test network.');
web3.eth.defaultAccount = web3.eth.accounts[0];
if(!web3.eth.defaultAccount){
console.log('Log into metamask');
_Connect(callback);
}else{
// Success
console.log(`Web3 ETH Account: ${web3.eth.defaultAccount}`);
callback(false, web3.eth.defaultAccount);
}
break
default:
console.log('This is an unknown network.');
callback('Switch Network', null);
}
});
} else {
console.log(`Failed: Web3 instance required, try using MetaMask.`);
callback('Install Metamask', null);
}
}
Chrome 插入 MetaMask Web3 库时存在延迟,因此需要超时(1 秒超时应该足够了)。
超时后,检查 web3 全局对象是否存在,然后读取默认帐户。
如果它不存在,则插入您自己的 web3 对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.