Search code examples
javascriptethereumblockchaincdnethers.js

Cannot make connection to metamask


I want to make connection to metamask and get the account balance :

<!DOCTYPE html>
<html>
    <head>
        <title>Test ethereum metamask</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <script type="module">
            import { ethers } from "https://cdn.ethers.io/lib/ethers-5.2.esm.min.js";
            const provider = new ethers.providers.Web3Provider(window.ethereum);
            const balance = await provider.getBalance("0xE0552897c6495D7efb98F3823cd48bf19e703D0b");
        </script>
    </head>
    <body>
        test
    </body>
    <script type="text/javascript">
        console.log("========== balance =", balance);
    </script>
</html>

At runtime I get console errors : Uncaught ReferenceError: balance is not defined and Access to script at 'https://cdn.ethers.io/lib/ethers-5.2.esm.min.js' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource

So what is the problem ?


Solution

  • use cloudflare cdn and put the console.log("========== balance =", balance); into the first script. module scripts are defer by default

    <script type="module">
          import { ethers } from "https://cdnjs.cloudflare.com/ajax/libs/ethers/5.7.2/ethers.esm.js";
          const provider = new ethers.providers.Web3Provider(window.ethereum);
          const balance = await provider.getBalance(
            "0xE0552897c6495D7efb98F3823cd48bf19e703D0b"
          );
          console.log("========== balance =", balance);
    </script>
    

    From this github post

    A lot of projects are using production levels of bandwidth from the ethers CDN to load their JavaScript, which I can no longer afford to operate at that scale.

    If you are linking to cdn.ethers.io or cdn-cors.ethers.io, you should switch to using the relevant link provided on cdnjs.

    Feedback is welcome, and I apologize for the inconvenience.

    Thanks!