0

I noticed that my little vanilla JS script to get people to connect to my "dapp" works fine on desktop with metamask, but doesn't work with metamask mobile app.

It gives me an error as if the "Provider" was not set.

const provider = new ethers.providers.Web3Provider(window.ethereum);
const signer = provider.getSigner();
const connectbtn = document.querySelector('.connectbtn');
connectbtn.addEventListener('click',enabler);

async function enabler(){
    
        try {
  await ethereum.request({
    method: 'wallet_switchEthereumChain',
    params: [{ chainId: '0x38' }],
  });
} catch (switchError) {
  // This error code indicates that the chain has not been added to MetaMask.
  if (error.code === 4902) {
    try {
      await ethereum.request({
        method: 'wallet_addEthereumChain',
        params: [{ chainId: '0x38', rpcUrl: 'https://bsc-dataseed.binance.org/' /* ... */ }],
      });
    } catch (addError) {
      // handle "add" error
    }
  }
  // handle other "switch" errors
}
 doing();
 
};

async function doing() {
    await provider.send("eth_requestAccounts", []);

    
    
    let addressconnected = document.querySelector(".addressConnected") ;
    addressconnected.innerHTML =`Connected`;
    

    // console.log("Account:", await signer.getAddress());
}

1 Answer 1

4

Because window.ethereum does not exist on mobile. it's only available on desktop web browsers. i believe that there are several ways:

1- Try to connect to Metamask on mobile via wallet connect.

2- if you're using React, use @react-web3/core to interact with it in a convinent way.

3- the official docs recommends to use @metamask/detect-provider

Note: reach out this link

A tricky note: it seems connecting to a wallet via wallet connect on mobile, should requires us to switching your dApp's url to https. it happens to me after switching it with the same code :)

If it's useful vote up plz :)

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.