[Ethereum] Web3 not being detected – google chrome extension

metamaskreacttruffleweb3js

I am working on a google chrome extension that operates when a user opens up a new tab. Upon opening a new tab, my dapp should connect to the user's web3 provider. However, no web3 is being detected.

Everything works fine if deployed as a simple webpage.

I am just running into said issue when I try to operate my dapp as a chrome extension, with it beginning to run when opening a new tab.

Here is truffle-react's setup which I did not edit for retrieving web3:

let getWeb3 = new Promise(function(resolve, reject) {
// Wait for loading completion to avoid race conditions with web3 
injection timing.
window.addEventListener('load', function() {
var results
var web3 = window.web3

// Checking if Web3 has been injected by the browser (Mist/MetaMask)
if (typeof web3 !== 'undefined') {
  // Use Mist/MetaMask's provider.
  web3 = new Web3(web3.currentProvider)

  results = {
    web3: web3
  }

  console.log('Injected web3 detected.');

  resolve(results)
} else {
  // Fallback to localhost if no web3 injection. We've configured this to
  // use the development console's port by default.
  var provider = new Web3.providers.HttpProvider('http://127.0.0.1:9545')

  web3 = new Web3(provider)

  results = {
    web3: web3
  }

  console.log('No web3 instance injected, using Local web3.');

  resolve(results)
}
})
})

Best Answer

This code checks for check for instance already available in window

var web3 = window.web3

If found, check for Mist/Metamask or any other provider, and return web3, and console outputs to 'Injected web3 detected.'

// Use Mist/MetaMask's provider.
  web3 = new Web3(web3.currentProvider)

  results = {
    web3: web3
  }

  console.log('Injected web3 detected.');

else if web3 instance is not found, this code fallback to localhost node web3 provider, so console outputs to 'No web3 instance injected, using Local web3.'

// Fallback to localhost if no web3 injection. We've configured this to
  // use the development console's port by default.
  var provider = new Web3.providers.HttpProvider('http://127.0.0.1:9545')

  web3 = new Web3(provider)

  results = {
    web3: web3
  }

  console.log('No web3 instance injected, using Local web3.');

As in your case you are not running local ethereum node, it is throwing error.

But as suggested by me, you have replaced localhost link with infura link.

Now there is no error.Why? because web3 has been injected.

But still console output is same, it's because console command still is same.

 console.log('No web3 instance injected, using Local web3.');

To check whether web3 has been instantiated & injected, just check web3 version

console.log(web3.version.api) // for web3 0.2x.x

or

console.log(web3.version) // for web3 1.0
Related Topic