![](/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.