On a previous version of web3js it was just

document.write(web3.eth.blockNumber + "<br><br>");

and it outputs it in the section of the page where the script is as seen in the infura example tutorial here

But in v1.0.0 it returns "undefined" and displays that on the screen.

from the documentation the new getBlockNumber method is


I have tried

               web3.eth.getBlockNumber(function (error, result) {

But that just removed all other html from the page and wrote the block number.

I just want to be able to output the current block number to the screen at a particular html element. Can anyone help me out?

I don't know javascript so web3 is obviously a bit of a struggle for me. Still struggling to wrap my head around promises, callbacks, etc.

BAsically I think my problem is not understanding why this method requires a callback, or what the callback is supposed to be.

I'd really appreciate any help. Thanks guys.

1 Answer 1

  1. create a div element (in this case it's div with id "blockNumber") in your index.html file to hold the block number:

    <div id="blockNumber"></div>
  2. then try the following in your front-end JS code:

    setInterval(function () {
      // block number of latest mined block
      web3.eth.getBlockNumber().then(data => {
        document.getElementById('blockNumber').innerHTML = data;
    }, 3000);

Note: if you just want to get the latest block number only once, you put the above code into a normal function without time interval.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.