'window.solana not found on js web3

I want to connect a Solana wallet (phantom or any other) to a web aplication through the js web3 library. I've read docs for most wallets and it seems like it's just as simple as await window.solana.request({ method: "connect" }); but window.solana is undefined in my case. When I do console.log(window) I can see the solana value with all its corresponding keys and values. How can I do this?



Solution 1:[1]

I've found a working code that solved my issue. I am not sure what was the issue as I'm not very experienced with js, but the following code lets me connect to phantom. I found this on StackOverflow on a similar thread, although I belive the original answer is missing some brackets. Solana : Adding Sollet / Phantom Wallet Connect to my website - Steps?

const getProvider = async () => {
    if ("solana" in window) {
      await window.solana.connect(); // opens wallet to connect to

      const provider = window.solana;
      if (provider.isPhantom) {
        console.log("Is Phantom installed?  ", provider.isPhantom);
        return provider;
      }
    } else {
      document.write('Install https://www.phantom.app/');
    }
};

window.onload = () => {

    getProvider().then(provider => {
        console.log('key', provider.publicKey.toString())
    })
    .catch(function(error){
        console.log(error)
    });

}

Solution 2:[2]

With your current implementation, everytime you refresh the app, you will get pop up to connect to the wallet. Instead you add {onlyIfTrusted:true} option to connect.

const getProvider = async () => { if ("solana" in window) { await window.solana.connect({onlyIfTrusted:true}); // opens wallet to connect to

  const provider = window.solana;
  if (provider.isPhantom) {
    console.log("Is Phantom installed?  ", provider.isPhantom);
    return provider;
  }
} else {
  document.write('Install https://www.phantom.app/');
}
};

then instead of getting pop up when you reload the app, write a connection function to handle the connection when a user clicks on the button

const connectToWallet=async ()=>{
    const {solana}=window
    if(solana){
      const response=await solana.connect()
      console.log('address',response.publicKey.toString())
      
    }
  }


<button onClick={connectToWallet}  >
    Connect to Wallet
    </button>

Now once user is connected, when you reload the app, it you wont get pop up to connect to the wallet

Sources

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

Source: Stack Overflow

Solution Source
Solution 1 ZygD
Solution 2 Yilmaz