Commit 4918646d authored by Stefy Spora's avatar Stefy Spora

Fix MetaMask detection in popup context

- Remove FetLife page requirement for Web3 donations
- Remove call to non-existent checkMetaMaskDirect() function
- Simplify Web3 donation event listener to work directly in popup context
- Fix conflicting event listeners that were causing MetaMask detection failure
- Web3 donations now work on any website, not just FetLife pages
parent 17f26d23
...@@ -22,7 +22,7 @@ document.addEventListener('DOMContentLoaded', function() { ...@@ -22,7 +22,7 @@ document.addEventListener('DOMContentLoaded', function() {
const stopBtn = document.getElementById('stop-btn'); const stopBtn = document.getElementById('stop-btn');
const statusDiv = document.getElementById('status'); const statusDiv = document.getElementById('status');
const progressDiv = document.getElementById('progress'); const progressDiv = document.getElementById('progress');
let isRunningBulk = false; let isRunningBulk = false;
let shouldStop = false; let shouldStop = false;
...@@ -30,7 +30,7 @@ document.addEventListener('DOMContentLoaded', function() { ...@@ -30,7 +30,7 @@ document.addEventListener('DOMContentLoaded', function() {
statusDiv.textContent = message; statusDiv.textContent = message;
statusDiv.className = `status ${type}`; statusDiv.className = `status ${type}`;
statusDiv.style.display = 'block'; statusDiv.style.display = 'block';
// Hide status after 3 seconds unless it's an error or we're running bulk // Hide status after 3 seconds unless it's an error or we're running bulk
if (type !== 'error' && !isRunningBulk) { if (type !== 'error' && !isRunningBulk) {
setTimeout(() => { setTimeout(() => {
...@@ -82,7 +82,7 @@ document.addEventListener('DOMContentLoaded', function() { ...@@ -82,7 +82,7 @@ document.addEventListener('DOMContentLoaded', function() {
// Get the current active tab // Get the current active tab
const [tab] = await chrome.tabs.query({ active: true, currentWindow: true }); const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
if (!tab.url.includes('fetlife.com')) { if (!tab.url.includes('fetlife.com')) {
showStatus('Please navigate to FetLife first', 'error'); showStatus('Please navigate to FetLife first', 'error');
enableButton(); enableButton();
...@@ -98,7 +98,7 @@ document.addEventListener('DOMContentLoaded', function() { ...@@ -98,7 +98,7 @@ document.addEventListener('DOMContentLoaded', function() {
}); });
const result = results[0].result; const result = results[0].result;
if (result.success) { if (result.success) {
showStatus(result.message, 'success'); showStatus(result.message, 'success');
} else { } else {
...@@ -123,7 +123,7 @@ document.addEventListener('DOMContentLoaded', function() { ...@@ -123,7 +123,7 @@ document.addEventListener('DOMContentLoaded', function() {
// Get the current active tab // Get the current active tab
const [tab] = await chrome.tabs.query({ active: true, currentWindow: true }); const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
if (!tab.url.includes('fetlife.com')) { if (!tab.url.includes('fetlife.com')) {
showStatus('Please navigate to FetLife first', 'error'); showStatus('Please navigate to FetLife first', 'error');
enableBulkButtons(); enableBulkButtons();
...@@ -148,7 +148,7 @@ document.addEventListener('DOMContentLoaded', function() { ...@@ -148,7 +148,7 @@ document.addEventListener('DOMContentLoaded', function() {
}); });
const result = results[0].result; const result = results[0].result;
if (result.success) { if (result.success) {
successCount++; successCount++;
} else { } else {
...@@ -168,7 +168,7 @@ document.addEventListener('DOMContentLoaded', function() { ...@@ -168,7 +168,7 @@ document.addEventListener('DOMContentLoaded', function() {
}); });
const nextResult = nextResults[0].result; const nextResult = nextResults[0].result;
if (!nextResult.hasNext) { if (!nextResult.hasNext) {
showStatus(`Completed! Processed ${pageCount} pages (${successCount} success, ${errorCount} errors)`, 'success'); showStatus(`Completed! Processed ${pageCount} pages (${successCount} success, ${errorCount} errors)`, 'success');
break; break;
...@@ -180,7 +180,7 @@ document.addEventListener('DOMContentLoaded', function() { ...@@ -180,7 +180,7 @@ document.addEventListener('DOMContentLoaded', function() {
} catch (error) { } catch (error) {
errorCount++; errorCount++;
console.error(`Error on page ${pageCount}:`, error); console.error(`Error on page ${pageCount}:`, error);
// Try to continue to next page even if current page failed // Try to continue to next page even if current page failed
try { try {
const nextResults = await chrome.scripting.executeScript({ const nextResults = await chrome.scripting.executeScript({
...@@ -227,7 +227,7 @@ document.addEventListener('DOMContentLoaded', function() { ...@@ -227,7 +227,7 @@ document.addEventListener('DOMContentLoaded', function() {
web3Status.textContent = message; web3Status.textContent = message;
web3Status.style.color = isError ? '#f44336' : '#4CAF50'; web3Status.style.color = isError ? '#f44336' : '#4CAF50';
web3Status.style.display = 'block'; web3Status.style.display = 'block';
setTimeout(() => { setTimeout(() => {
web3Status.style.display = 'none'; web3Status.style.display = 'none';
}, 5000); }, 5000);
...@@ -269,7 +269,7 @@ document.addEventListener('DOMContentLoaded', function() { ...@@ -269,7 +269,7 @@ document.addEventListener('DOMContentLoaded', function() {
} }
const donationAddress = '0xdA6dAb526515b5cb556d20269207D43fcc760E51'; const donationAddress = '0xdA6dAb526515b5cb556d20269207D43fcc760E51';
// Prepare transaction parameters (user can modify amount in wallet) // Prepare transaction parameters (user can modify amount in wallet)
const transactionParameters = { const transactionParameters = {
to: donationAddress, to: donationAddress,
...@@ -295,10 +295,10 @@ document.addEventListener('DOMContentLoaded', function() { ...@@ -295,10 +295,10 @@ document.addEventListener('DOMContentLoaded', function() {
} }
return { success: true, message: `Transaction sent! Hash: ${txHash.substring(0, 10)}...` }; return { success: true, message: `Transaction sent! Hash: ${txHash.substring(0, 10)}...` };
} catch (error) { } catch (error) {
console.error('Web3 donation error:', error); console.error('Web3 donation error:', error);
if (error.code === 4001 || (error.message && error.message.includes('User denied'))) { if (error.code === 4001 || (error.message && error.message.includes('User denied'))) {
return { success: false, message: 'Transaction cancelled by user.' }; return { success: false, message: 'Transaction cancelled by user.' };
} else if (error.code === -32602) { } else if (error.code === -32602) {
...@@ -309,93 +309,24 @@ document.addEventListener('DOMContentLoaded', function() { ...@@ -309,93 +309,24 @@ document.addEventListener('DOMContentLoaded', function() {
} }
} }
// Web3 donation event listener
web3DonateBtn.addEventListener('click', async function() { web3DonateBtn.addEventListener('click', async function() {
try { try {
web3DonateBtn.disabled = true; web3DonateBtn.disabled = true;
web3DonateBtn.textContent = '🔄 Connecting...'; web3DonateBtn.textContent = '🔄 Connecting...';
// 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 MetaMask is available via direct injection
const isMetaMaskAvailable = await checkMetaMaskDirect(tab.id);
if (!isMetaMaskAvailable) {
showWeb3Status('MetaMask not detected. Please ensure MetaMask is installed and unlocked.', true);
return;
}
// Then 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'
});
showWeb3Status(response.message, !response.success); // Execute Web3 donation directly in popup context
const result = await executeWeb3Donation();
showWeb3Status(result.message, !result.success);
} catch (error) { } catch (error) {
console.error('Web3 donation error:', error); console.error('Web3 donation error:', error);
showWeb3Status('Failed to initiate donation: ' + (error.message || 'Unknown error'), 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 { } finally {
web3DonateBtn.disabled = false; web3DonateBtn.disabled = false;
web3DonateBtn.textContent = '🦊 Donate with MetaMask'; web3DonateBtn.textContent = '🦊 Donate with MetaMask';
} }
}); });
// Remove the old web3 event listener and add the new one
const oldBtn = document.getElementById('web3-donate-btn');
if (oldBtn) {
oldBtn.replaceWith(oldBtn.cloneNode(true));
const newBtn = document.getElementById('web3-donate-btn');
newBtn.addEventListener('click', async function() {
try {
newBtn.disabled = true;
newBtn.textContent = '🔄 Connecting...';
// Execute Web3 donation directly in popup context
const result = await executeWeb3Donation();
showWeb3Status(result.message, !result.success);
} catch (error) {
console.error('Web3 donation error:', error);
showWeb3Status('Failed to initiate donation: ' + (error.message || 'Unknown error'), true);
} finally {
newBtn.disabled = false;
newBtn.textContent = '🦊 Donate with MetaMask';
}
});
}
}); });
// Function to find and click the next link // Function to find and click the next link
...@@ -407,14 +338,14 @@ function findAndClickNext() { ...@@ -407,14 +338,14 @@ function findAndClickNext() {
link.textContent.trim().includes('next ›') || link.textContent.trim().includes('next ›') ||
link.textContent.trim() === 'next' link.textContent.trim() === 'next'
); );
if (nextLinks.length === 0) { if (nextLinks.length === 0) {
return { hasNext: false, message: 'No next link found' }; return { hasNext: false, message: 'No next link found' };
} }
// Click the first next link found // Click the first next link found
nextLinks[0].click(); nextLinks[0].click();
return { hasNext: true, message: 'Clicked next link' }; return { hasNext: true, message: 'Clicked next link' };
} catch (error) { } catch (error) {
...@@ -427,19 +358,19 @@ function executePrivacyUpdate() { ...@@ -427,19 +358,19 @@ function executePrivacyUpdate() {
// Function to extract media ID and type from URL // Function to extract media ID and type from URL
function getMediaInfo() { function getMediaInfo() {
const url = window.location.href; const url = window.location.href;
// Handle both direct URLs and username-based URLs // Handle both direct URLs and username-based URLs
// Direct: https://fetlife.com/videos/123 or https://fetlife.com/pictures/123 // Direct: https://fetlife.com/videos/123 or https://fetlife.com/pictures/123
// Username: https://fetlife.com/username/videos/123 or https://fetlife.com/username/pictures/123 // Username: https://fetlife.com/username/videos/123 or https://fetlife.com/username/pictures/123
const videoMatch = url.match(/https:\/\/fetlife\.com\/(?:[^\/]+\/)?videos\/(\d+)/); const videoMatch = url.match(/https:\/\/fetlife\.com\/(?:[^\/]+\/)?videos\/(\d+)/);
const pictureMatch = url.match(/https:\/\/fetlife\.com\/(?:[^\/]+\/)?pictures\/(\d+)/); const pictureMatch = url.match(/https:\/\/fetlife\.com\/(?:[^\/]+\/)?pictures\/(\d+)/);
if (videoMatch) { if (videoMatch) {
return { type: 'video', id: videoMatch[1] }; return { type: 'video', id: videoMatch[1] };
} else if (pictureMatch) { } else if (pictureMatch) {
return { type: 'picture', id: pictureMatch[1] }; return { type: 'picture', id: pictureMatch[1] };
} }
return null; return null;
} }
...@@ -449,12 +380,12 @@ function executePrivacyUpdate() { ...@@ -449,12 +380,12 @@ function executePrivacyUpdate() {
if (metaTag) { if (metaTag) {
return metaTag.getAttribute('content'); return metaTag.getAttribute('content');
} }
const csrfInput = document.querySelector('input[name="authenticity_token"]'); const csrfInput = document.querySelector('input[name="authenticity_token"]');
if (csrfInput) { if (csrfInput) {
return csrfInput.value; return csrfInput.value;
} }
return null; return null;
} }
......
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