3

I'm trying to get the network ID from the Web3 object on the client side (i.e. - while running Javascript code in the browser). I have code that confirms that the object exists and it does. I have the Metamask extension installed and configured in Chrome. I have clicked on the extension and I am definitely connected to the Ganache network client (Localhost 8545). However, every time I call **web3.version.getNetwork()** the result is **undefined**. Does anyone know why this is happening and how I can fix it?

UPDATE: I tried the same test with web3.eth.getAccounts() and that too is coming back undefined. I'm guessing I'll get the same result with any of the Web3 methods/properties I try.

 // Make sure the Web3.js object has been defined. web3_helpers.web3AndMetamaskCheck(); if (typeof gameDetailsObj == 'undefined' || gameDetailsObj == null) throw new Error(errPrefix + 'The game details object is unassigned.'); if (typeof currentUserObj == 'undefined' || currentUserObj == null) throw new Error(errPrefix + 'The current user object is unassigned.'); // >>>>> getNetworkCall is ALWAYS 'undefined'. var getNetworkCall = web3.version.getNetwork(); 

2 Answers 2

2

Yes, your right it will return undefined. Because web3.version.getNetwork() is not a sync method and it will not return any value. In javascript, If function is not return any method it will init varible is undefined. Refer below code for ref:

web3.version.getNetwork(function(err, networkId){ switch(networkId){ case "1": //TODO your logic... break; default: //If neteork id is not mattching... } }); 
0

For those looking for an up-to-date answer (April 2024):

You should be using chain ids rather than network ids. More on that on this post by Pedro Gomes (WalletConnect's founder).

To get the chain id with web3.js 4.x, you should use web3.eth.getChainId() instead, and map that to the network name yourself:

const SUPPORTED_CHAINS_NAMES: Record<number, string> = { 1: 'Ethereum Mainnet', 11155111: 'Sepolia', }; const chainId = Number(await web3.eth.getChainId()); const chainName = SUPPORTED_CHAINS_NAMES[chainId] || 'Unsupported Chain'; 

Or use a library like eth-chains to get up-to-date chain information, instead of manually mapping the chain id:

const chainId = Number(await web3.eth.getChainId()); const chainInfo = chains.getById(chainId) || null; const chainName = chainInfo?.name || 'Unsupported Chain'; 

Also, see web3.js' migration guide.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.