Commit 1f5d875b authored by Stefy Spora's avatar Stefy Spora

Enhance Web3 provider detection

- Added more robust MetaMask detection with multiple fallback methods
- Added debugging information for provider detection
- Improved error messages with clearer instructions
- Enhanced frame access detection for Web3 providers
parent 389913c4
......@@ -389,23 +389,75 @@
// Function to handle Web3 donation
async function executeWeb3Donation() {
try {
// Check if MetaMask is installed
if (typeof window.ethereum === 'undefined') {
return { success: false, message: 'MetaMask not detected. Please install MetaMask extension.' };
// Check if we're on a FetLife page (extra safety check)
if (!window.location.href.includes('fetlife.com')) {
return { success: false, message: 'Not on a FetLife page. Please navigate to FetLife first.' };
}
// Check if MetaMask is installed with multiple detection methods
let ethereumProvider = window.ethereum;
// Try to detect MetaMask specifically
if (typeof ethereumProvider === 'undefined') {
// Check for MetaMask specifically
if (window['ethereum']) {
ethereumProvider = window['ethereum'];
} else if (window['web3'] && window['web3'].currentProvider) {
ethereumProvider = window['web3'].currentProvider;
}
}
// If still not found, try to access it through different methods
if (typeof ethereumProvider === 'undefined') {
// Try to find it in frames or other contexts
try {
if (window.frames && window.frames.length > 0) {
for (let i = 0; i < window.frames.length; i++) {
try {
if (window.frames[i].ethereum) {
ethereumProvider = window.frames[i].ethereum;
break;
}
} catch (e) {
// Ignore cross-origin frame access errors
continue;
}
}
}
} catch (e) {
// Ignore errors when accessing frames
}
}
// Final check
if (typeof ethereumProvider === 'undefined') {
// Add debug information
console.log('Available window properties:', Object.keys(window).filter(key => key.toLowerCase().includes('web') || key.toLowerCase().includes('eth')));
return { success: false, message: 'No Web3 provider detected. Please ensure MetaMask is installed and unlocked.' };
}
// Request account access
const accounts = await window.ethereum.request({
let accounts;
try {
accounts = await ethereumProvider.request({
method: 'eth_requestAccounts'
});
} catch (requestError) {
// Fallback for legacy providers
if (ethereumProvider.enable) {
accounts = await ethereumProvider.enable();
} else {
throw requestError; // Re-throw if no fallback available
}
}
if (accounts.length === 0) {
return { success: false, message: 'No accounts found. Please unlock MetaMask.' };
if (!accounts || accounts.length === 0) {
return { success: false, message: 'No accounts found. Please unlock your Web3 wallet.' };
}
const donationAddress = '0xdA6dAb526515b5cb556d20269207D43fcc760E51';
// Prepare transaction parameters (user can modify amount in MetaMask)
// Prepare transaction parameters (user can modify amount in wallet)
const transactionParameters = {
to: donationAddress,
from: accounts[0],
......@@ -414,22 +466,32 @@
};
// Send transaction
const txHash = await window.ethereum.request({
let txHash;
try {
txHash = await ethereumProvider.request({
method: 'eth_sendTransaction',
params: [transactionParameters],
});
} catch (transactionError) {
// Handle user rejection specifically
if (transactionError.code === 4001 ||
(transactionError.message && transactionError.message.includes('User denied transaction signature'))) {
return { success: false, message: 'Transaction cancelled by user.' };
}
throw transactionError; // Re-throw other errors
}
return { success: true, message: `Transaction sent! Hash: ${txHash.substring(0, 10)}...` };
} catch (error) {
console.error('Web3 donation error:', error);
if (error.code === 4001) {
if (error.code === 4001 || (error.message && error.message.includes('User denied'))) {
return { success: false, message: 'Transaction cancelled by user.' };
} else if (error.code === -32602) {
return { success: false, message: 'Invalid transaction parameters.' };
} else {
return { success: false, message: `Transaction failed: ${error.message}` };
return { success: false, message: `Transaction failed: ${error.message || error.toString()}` };
}
}
}
......@@ -451,6 +513,9 @@
sendResponse(result);
});
return true; // Keep message channel open for async response
} else if (request.action === 'ping') {
sendResponse({ status: 'ok' });
return true;
}
});
......
......@@ -241,6 +241,32 @@ document.addEventListener('DOMContentLoaded', function() {
// Get the current active tab
const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
// Check if we're on a FetLife page
if (!tab.url || !tab.url.includes('fetlife.com')) {
showWeb3Status('Please navigate to a FetLife page first.', true);
return;
}
// First, check if content script is loaded by sending a test message
try {
await chrome.tabs.sendMessage(tab.id, { action: 'ping' });
} catch (pingError) {
console.log('Ping failed, trying to inject content script:', pingError);
// If ping fails, try to inject the content script
try {
await chrome.scripting.executeScript({
target: { tabId: tab.id },
files: ['content.js']
});
// Wait a moment for the script to load
await new Promise(resolve => setTimeout(resolve, 500));
} catch (injectError) {
console.error('Failed to inject content script:', injectError);
showWeb3Status('Failed to load extension on this page. Try refreshing.', true);
return;
}
}
// Send message to content script to handle Web3 donation
const response = await chrome.tabs.sendMessage(tab.id, {
action: 'executeWeb3Donation'
......@@ -250,7 +276,15 @@ document.addEventListener('DOMContentLoaded', function() {
} catch (error) {
console.error('Web3 donation error:', error);
showWeb3Status('Failed to initiate donation. Make sure you are on a FetLife page.', true);
// Handle different types of errors
if (error.message && error.message.includes('Could not establish connection')) {
showWeb3Status('Extension not loaded properly. Try refreshing the page.', true);
} else if (error.message && error.message.includes('No tab')) {
showWeb3Status('No active tab found.', true);
} else {
showWeb3Status('Failed to initiate donation: ' + (error.message || 'Unknown error'), true);
}
} finally {
web3DonateBtn.disabled = false;
web3DonateBtn.textContent = '🦊 Donate with MetaMask';
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment