'Connect to MetaMask via chrome extension
I am making a chrome extension that requires MetaMask authentication.
I started developing it as a web application, but as a chrome extension, it doesn't detect MetaMask...
This is my web application code right now:
function toggleButton() {
const loginButton = document.getElementById("login-button");
if (!window.ethereum) {
loginButton.innerText = "Install MetaMask";
loginButton.addEventListener("click", () => {
window.open("https://metamask.io");
});
return false;
}
loginButton.addEventListener("click", loginWithMetaMask);
}
async function loginWithMetaMask() {
const accounts = await window.ethereum.request({ method: "eth_requestAccounts" }).catch((e) => {
console.error(e.message);
return;
});
if (!accounts) {
return;
}
const userWallet = document.getElementById("user-wallet");
userWallet.innerText = accounts[0];
}
window.addEventListener("DOMContentLoaded", toggleButton);
Is there a way to migrate the web application to a chrome extension?
Solution 1:[1]
This is how to do it.
Install metamask-extension-provider in your project https://github.com/MetaMask/extension-provider You will need to use browserify to compile your plugin.
Create a custom connector like this
class customConnector extends Moralis.AbstractWeb3Connector {
async activate() {
const provider = createMetaMaskProvider();
if (!provider) {
console.error("MetaMask provider not detected.");
throw new Error("MetaMask provider not detected.");
}
const [accounts, chainId] = await Promise.all([
provider.request({
method: 'eth_requestAccounts',
}),
provider.request({ method: 'eth_chainId' }),
]);
const account = accounts[0] ? accounts[0].toLowerCase() : null;
this.chainId = provider.chainId;
this.account = provider.selectedAddress;
this.provider = provider;
this.subscribeToEvents(provider);
return { provider, chainId, account };
}
}
Now you can authenticate using MetaMask like this
Moralis.authenticate({ connector: customConnector })
Solution 2:[2]
I have created a small boilerplate of chrome extension with react and added metamask login and web3 support.
https://github.com/shaheem-khanzada/chrome-extension-react-metamask-boilerplate
so the problem is we cannot access window.eth... directly in the extension that is why metamask created a module called metamask-extension-provider but in order to run this we need to use browserify compiler so in simple words, we need to write our own compiler that's why I created this boilerplate to help others it uses gulp to create task and then bundle files using browserify and babelify
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 | emorling |
Solution 2 |