程式麻瓜打造區塊鏈網站11-連接&檢查Metamask(request metamask conncetion)

當我們製作了一個網頁,要得到網頁訪客的帳戶資訊且與區塊鏈互動,就需要請求連接metamask,按下以下按鈕能夠請求連結,請將他的程式碼放到網頁裡。

if (typeof window.ethereum !== ‘undefined’) {
console.log(‘MetaMask is installed!’);
}else{
alert(“Please install MataMask”);
}

上面這段程式碼是檢查訪客是否有安裝metamask若沒安裝就會跳出警告

const ethereumButton = document.querySelector(‘.enableEthereumButton’);ethereumButton.addEventListener(‘click’, () => {
//Will Start the metamask extension
ethereum.request({ method: ‘eth_requestAccounts’ });
});

上方程式碼是讓當class為enableEthereumButton的按鈕被按下的時候請求連接metamask,請求連接的程式碼是下面這行

ethereum.request({ method: ‘eth_requestAccounts’ });

如果直接將它貼在網頁裡,當網頁被開啟或是重新整理就會自動請求,但是metamask不贊同用這樣的方法,所以還是乖乖放個按鈕比較保險。