[Ethereum] Accessing web3 object in Chrome terminal using React

reactweb3js

I am receiving a "not defined" error when trying to access the web3 object in Chrome terminal. My current setup:

  • running testrpc
  • web3 object successfully instantiated in App.js
  • built app using React
  • using Chrome incognito window

I would like to be able to access my contract through the Chrome terminal but when I try to set the web3 variable in terminal here:

var web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:8545'));

I receive the error Uncaught ReferenceError: Web3 is not defined in Chrome console.

In my App.js file, I have the following: import Web3 from 'web3';. When I set the variable in App.js, console.log(web3) outputs the object correctly. When I try to add import Web3 from 'web3'; in Chrome terminal, I get the error Uncaught SyntaxError: Unexpected token import.

After doing a little research it looks like I might need to use require and Browserify to use the web3 library correctly in Chrome terminal. Are there other ways to use the web3js in React in Chrome terminal using my current setup?

Best Answer

In order to use web3 in the Chrome console:

  1. Go to a "real" web page, for example www.google.com
  2. In the developer tools/console enter:
ethereum.enable()
  1. In the metamask popup press Connect
  2. In the developer tools/console enter the command below to see you can access the web3 object, which is inserted by metamask.
web3.version

If you want to use a newer version of web3.js: this example uses browserify:
problem connecting web3 v 1.2.1 with metamask : 'currentProvider' of undefined

Related Topic