2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

[web3js]Metamaskのネットワーク変更を検知する

Last updated at Posted at 2022-10-23

Metamaskはメインネットやテストネットの切り替えが自由にできますが、ネットワーク切り替え時にフロント側で自動で検知するサンプルを作成しました。

サンプル

テストネットやアカウント変更時に表示を変えるサンプルです。
※Chrome拡張のMetamaskをインストールしないと起動しませんのでご注意ください

See the Pen web3 changed chain by Kurokiri (@kurokiri) on CodePen.

処理説明

過去はgetNetwork等でネットーワーク情報を取得できたみたいですが、現在(2022年10月)はgetChainIdが推奨されているので下記みたいにあらかじめ必要なチェーン情報を定義しておいてIDで取得する方法がよさそうです。

const Chains = {
  1: "Mainnet",
  3: "Ropsten[Deprecate]",
  4: "Rinkeby[Deprecate]",
  5: "Goerli",
  11155111: "Sepolia",
};

また、過去はネットワーク切り替えタイミングで自動でブラウザリロードが走っていたみたいですが、現在は切り替えてもリロードされないのでsetIntervalで定期実行し、検知する必要があります。

  // ネットワーク切り替えを検知
  setInterval(async function () {
    const web3 = new Web3(window.ethereum);
    const chengedNetwork = await web3.eth.getChainId();
    if (currentNetwork !== chengedNetwork) {
      currentNetwork = chengedNetwork;
      const networkTextArea = document.getElementById('network');
      networkTextArea.textContent = "選択しているネットワークは" + Chains[currentNetwork] + "です";
    }
  }, 1000);

まとめ

Metamaskのネットワークやアカウントはユーザーが自由に切り替えられるため、切り替わったタイミングで何かしら処理を分岐させる必要がある場合の参考になったら嬉しいです。
また、現在このやり方は古いとか、こういうやり方もあるよ!みたいなコメントあればぜひお願いします!

リファレンス

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?