'Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist while trying to connect metamask

There seems to be a problem while connecting to the web application. enter image description here

At the first initialization of the application it throws this error but when, I refresh the page metamask pops up normally. Is there any workaround to get rid of this?

I am using angular to develop the web application and ethers library to fetch data from smart contract.

Code:

async connectmetamask() {
    //Fetching the data from smart contract
    try{
      const provider = new ethers.providers.Web3Provider(window.ethereum);
      this.signer = provider.getSigner();
    }catch{
      this.loader.stop()
      this.toastr.error("Metamask not found !")
    }
    // const provider = new ethers.providers.Web3Provider(window.ethereum);
    // this.signer = provider.getSigner();
    await window.ethereum.request({ method: 'eth_requestAccounts' })
    this.loader.stop()
    this.signerAddress = await this.signer.getAddress()
    this.electionContract = new ethers.Contract(addresses.electioncontract, Election.abi, this.signer);
    this.signerAddress = await this.signer.getAddress()
    this.getdata()
  }


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source