TransWikia.com

Use web3.js without MetaMask

Ethereum Asked on November 20, 2021

I have

<script src="https://cdnjs.cloudflare.com/ajax/libs/web3/1.2.9/web3.min.js"></script>

How to use this web3.js on browsers without MetaMask (for read-only Ethereum queries):

const web3 = new Web3(window.web3.currentProvider);

fails because window.web3 is undefined.

I think, I can initialize Web3 by specifying a provider manually. But how to decide what exactly to pass as the argument to new Web3 (for mainnet and for rinkeby)?

I need to use my own Infura account? Maybe I can pass the MetaMask’s account (is it legal? what is the MetaMask provider URLs for mainnet and for rinkeby)?

2 Answers

Also you can use infura

Check this page

And use this code:

web3 = new Web3(new Web3.providers.HttpProvider("https://ropsten.infura.io/v3/3c6/*your own Id from infura site after creating project*/753")); 

Answered by owl on November 20, 2021

  1. Notice that new API is available:
// Legacy dapp browsers...
if (window.web3 !== undefined) {
    const provider = new Web3.providers.HttpProvider(window.web3.currentProvider);
    const web3 = new Web3(provider);
}

// Modern dapp browsers...
if (window.ethereum !== undefined) {
  const provider = new Web3.providers.HttpProvider(window.ethereum);
  const web3 = new Web3(provider);
}

More details:


  1. In the browser, it is better not to use own account, but only a public Infura API.
  2. Yes, you can pass the MetaMask's account.
  3. Listen to chainChanged event to handle chain change: https://docs.metamask.io/guide/ethereum-provider.html#using-the-provider

Answered by MentatX on November 20, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP