Skip to content
TheChatArchiveThe Chat Archive
Perplexitysonar-pro-high· PerplexityHugging Face LMArena Search Arena 24K

// background.js const MATCHTHRESHOLD = 75; const TITLEMATCHTHRESHOLD = 60; const…

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with Perplexitysonar-pro’s answer.
  1. User

    // background.js const MATCH_THRESHOLD = 75; const TITLE_MATCH_THRESHOLD = 60; const CONTENT_MATCH_THRESHOLD = 50; const MAX_HISTORY_ITEMS = 3; const NOTIFICATION_TIMEOUT = 15000;

    let pendingDownloads = new Map(); let downloadNotifications = new Map(); let suggestCallbacks = new Map(); let contentAnalysisResults = new Map(); // Store content analysis results

    chrome.runtime.onInstalled.addListener(() => { console.log("Download Organizer Extension installed"); });

    chrome.runtime.onMessage.addListener((message, sender, sendResponse) => { if (message.action === "contentAnalysis") { // Store content analysis result, keyed by tab ID (or initiator for downloads) console.log("Received content analysis from tab:", sender.tab ? sender.tab.id : "no tab"); console.log("Content Length:", message.content.length); // Log content length contentAnalysisResults.set(sender.tab ? sender.tab.id : message.initiator, message.content);

    }
    

    });

    chrome.downloads.onDeterminingFilename.addListener((downloadItem, suggest) => { console.log("Download started:", downloadItem.filename, downloadItem.url);

    pendingDownloads.set(downloadItem.id, { downloadItem, suggest });
    suggestCallbacks.set(downloadItem.id, suggest);
    
    processDownload(downloadItem).catch(error => {
        console.error("Error processing download:", error);
        callSuggestSafely(downloadItem.id, {});
    });
    
    return true;
    

    });

    async function processDownload(downloadItem) { const { gameConfigs } = await chrome.storage.sync.get('gameConfigs'); if (!gameConfigs) { callSuggestSafely(downloadItem.id, {}); return; }

    const matchResults = await analyzeDownload(downloadItem, gameConfigs);
    
    if (matchResults.every(result => result.matchPercentage === 0)) {
        console.log("No matches found (0%), using default location");
        callSuggestSafely(downloadItem.id, {});
        return;
    }
    
    const bestMatch = matchResults[0];
    // Check filename, url, title, and content
    if (bestMatch.filenameMatchPercentage >= MATCH_THRESHOLD || bestMatch.urlMatchPercentage >= MATCH_THRESHOLD || bestMatch.titleMatchPercentage >= TITLE_MATCH_THRESHOLD || bestMatch.contentMatchPercentage >= CONTENT_MATCH_THRESHOLD) {
        console.log(`Using best match automatically: ${bestMatch.name} (Filename: ${Math.round(bestMatch.filenameMatchPercentage)}%, URL: ${Math.round(bestMatch.urlMatchPercentage)}%, Title: ${Math.round(bestMatch.titleMatchPercentage)}%, Content: ${Math.round(bestMatch.contentMatchPercentage)}%, Overall: ${Math.round(bestMatch.matchPercentage)}%)`);
        const suggestedFilename = getSuggestedFilename(downloadItem, bestMatch);
        callSuggestSafely(downloadItem.id, { filename: suggestedFilename, conflictAction: 'uniquify' });
        return;
    }
    
    showDownloadPathNotification(downloadItem, matchResults.slice(0, 2));
    

    }

    function getSuggestedFilename(downloadItem, match) { const baseFilename = downloadItem.filename.split('/').pop(); const relativePath = match.downloadPath.replace(/^[A-Z]:[\/]/, '').replace(/\/g, '/'); const normalizedPath = relativePath.endsWith('/') ? relativePath : relativePath + '/'; return normalizedPath + baseFilename; }

    function callSuggestSafely(downloadId, suggestion) { const suggest = suggestCallbacks.get(downloadId); if (suggest) { if (!suggestion.filename) { console.warn("Suggesting with an empty filename. Using default behavior."); suggestion = {}; // Ensure default behavior } suggest(suggestion); suggestCallbacks.delete(downloadId); } else { console.warn(No suggest callback found for download ID ${downloadId}); } }

    async function analyzeDownload(downloadItem, gameConfigs) { const parsedConfigs = gameConfigs.map(config => ({ ...config, keywordList: config.keywords.split(',').map(k => k.trim().toLowerCase()) }));

    // --- 1. Analyze Filename FIRST ---
    const filenameResults = analyzeFilename(downloadItem.filename, parsedConfigs);
    const highFilenameMatch = filenameResults.find(r => r.filenameMatchPercentage >= MATCH_THRESHOLD);
    if (highFilenameMatch) {
        console.log(`High filename match detected for ${highFilenameMatch.name} (${Math.round(highFilenameMatch.filenameMatchPercentage)}%), skipping further analysis.`);
        filenameResults.sort((a, b) => b.filenameMatchPercentage - a.filenameMatchPercentage);
        return filenameResults; // Return immediately if high filename match
    }
    
    
    // --- 2. Try to get tab information ---
    let tabInfo = null;
    if (downloadItem.initiator) {
        try {
            tabInfo = await getTabInfo(downloadItem.initiator);
            console.log("Tab Info:", tabInfo);
        } catch (error) {
            console.error("Error getting tab info:", error);
            // Fallback to history
        }
    }
    
    // --- 3. Analyze based on tab info or history ---
    let historyItems = [];
    if (!tabInfo) {
        historyItems = await getRecentHistory(MAX_HISTORY_ITEMS);
        console.log("History Items:", historyItems); // Log the history items
    }
    
    // --- 4. Analyze URLs and Titles ---
    const urlResults = await analyzeUrls(downloadItem.url, downloadItem.referrer, tabInfo, historyItems, parsedConfigs);
    const highTitleMatchResult = urlResults.find(r => r.titleMatchPercentage >= TITLE_MATCH_THRESHOLD);
    if (highTitleMatchResult) {
        console.log(`High title match detected for ${highTitleMatchResult.name} (${Math.round(highTitleMatchResult.titleMatchPercentage)}%), skipping content analysis if content threshold not also met.`);
        // DON'T return yet, we need to check content and combine results
    }
    
    
    // --- 5. Analyze Page Content (Always, but give priority to tabInfo) ---
    let contentResults = [];
    if (tabInfo) {
        // Use content analysis result if available, otherwise, request it
        if (contentAnalysisResults.has(tabInfo.id)) {
            const content = contentAnalysisResults.get(tabInfo.id);
             // Parse the content string back into a DOM tree.
            const doc = parseHtmlContent(content);
            contentResults = await analyzePageContent([{ title: tabInfo.title, url: tabInfo.url, doc: doc }], parsedConfigs);
            contentAnalysisResults.delete(tabInfo.id);  //consume it
        } else {
            // Inject content script to get the content (if not already retrieved)
            try {
                await injectContentScript(tabInfo.id, downloadItem.initiator); // Inject and wait
            } catch (error) {
                console.error("Failed to inject content script:", error);
            }
            if (contentAnalysisResults.has(tabInfo.id)) {
                 const content = contentAnalysisResults.get(tabInfo.id);
                // Parse the content string back into a DOM tree.
                const doc = parseHtmlContent(content);
    
                contentResults = await analyzePageContent([{ title: tabInfo.title, url: tabInfo.url, doc: doc }], parsedConfigs);
                contentAnalysisResults.delete(tabInfo.id);
            } else {
                console.warn("Content analysis not available for tab:", tabInfo.id);
                contentResults = await analyzePageContent([], parsedConfigs); // Use empty array as fallback
            }
        }
    } else {
        // Use history and content analysis results
        const itemsToAnalyze = [];
        for (let i = 0; i < historyItems.length && i < MAX_HISTORY_ITEMS; i++) {
            const item = historyItems[i];
            console.log(`Analyzing history item ${i + 1}:`, item); // Log each history item being analyzed
            if (contentAnalysisResults.has(item.id)) {
                const content = contentAnalysisResults.get(item.id);
                // Parse the content string back into a DOM tree.
                const doc = parseHtmlContent(content);
                console.log(`Content found for history item ${i + 1}, length: ${content.length}`); // Log content length
                itemsToAnalyze.push({ ...item, doc: doc }); //Store the doc
                contentAnalysisResults.delete(item.id);
            } else {
                itemsToAnalyze.push(item); //If no content, use the item.  analyzePageContent will handle.
            }
        }
        console.log("Items to Analyze (Content):", itemsToAnalyze); // Log the items prepared for content analysis
        contentResults = await analyzePageContent(itemsToAnalyze, parsedConfigs);
    
    }
    const highContentMatchResult = contentResults.find(r => r.contentMatchPercentage >= CONTENT_MATCH_THRESHOLD);
    
    // --- 6. Combine Results ---
    let combinedResults = combineResults(filenameResults, urlResults); // Combine filename and URL/Title
    combinedResults = combineResults(combinedResults, contentResults);   // Combine with content results
    
    if (highContentMatchResult) {
        console.log(`High content match detected for ${highContentMatchResult.name} (${Math.round(highContentMatchResult.contentMatchPercentage)}%).`);
    }
    
    combinedResults.sort((a, b) => b.matchPercentage - a.matchPercentage);
    return combinedResults;
    

    }

    // Helper function to safely parse HTML content function parseHtmlContent(htmlString) { const parser = new DOMParser(); try { const doc = parser.parseFromString(htmlString, "text/html"); return doc; } catch (error) { console.error("Error parsing HTML content:", error); return null; // Return null on error } }

    // UPDATED: In analyzeFilename, add debug logging by passing "filename" as the source. function analyzeFilename(filename, parsedConfigs) { const normalizedFilename = filename.toLowerCase(); const results = []; for (const config of parsedConfigs) { let matchCount = 0; for (const keyword of config.keywordList) { if (normalizedFilename.includes(keyword)) { console.debug(Match found: Keyword "${keyword}" found in filename: ${filename} (direct match)); matchCount++; } } const filenameMatchPercentage = config.keywordList.length > 0 ? Math.min(100, (matchCount / config.keywordList.length) * 100) : 0; results.push({ name: config.name, downloadPath: config.downloadPath, filenameMatchPercentage, matchPercentage: filenameMatchPercentage, urlMatchPercentage: 0, titleMatchPercentage: 0, contentMatchPercentage: 0 }); } return results; }

    //Combine Filename and Other results function combineResults(filenameResults, otherResults) { const combined = [...filenameResults]; // Start with filename results

    // Merge other results, updating matchPercentage if necessary
    for (const otherResult of otherResults) {
        const existing = combined.find(r => r.name === otherResult.name);
        if (existing) {
            // Update URL and title percentages, and recalculate overall matchPercentage
            existing.urlMatchPercentage = Math.max(existing.urlMatchPercentage, otherResult.urlMatchPercentage || 0); // Ensure 0 if undefined
            existing.titleMatchPercentage = Math.max(existing.titleMatchPercentage, otherResult.titleMatchPercentage || 0);
            existing.contentMatchPercentage = Math.max(existing.contentMatchPercentage, otherResult.contentMatchPercentage || 0); // Take max of content percentages
            existing.matchPercentage = Math.max(existing.filenameMatchPercentage, existing.urlMatchPercentage, existing.titleMatchPercentage, existing.contentMatchPercentage); // Include content in overall max
    
        } else {
            //This part should never happen as filename should contain every name
            combined.push(otherResult);
        }
    }
    return combined;
    

    }

    async function getTabInfo(initiator) { return new Promise((resolve, reject) => { // Try to find the tab based on the initiator URL chrome.tabs.query({}, (tabs) => { // Query ALL tabs const matchedTab = tabs.find(tab => tab.url && initiator && tab.url.startsWith(initiator.split('?')[0])); //Basic URL Matching

            if (!matchedTab) {
                reject(new Error("No matching tab found."));
                return;
            }
    
            // Inject content script to get the title
            chrome.scripting.executeScript({
                target: { tabId: matchedTab.id },
                func: () => document.title, // Get the title directly
            }, (results) => {
                if (chrome.runtime.lastError) {
                    reject(chrome.runtime.lastError);
                    return;
                }
                if (results && results[0] && results[0].result) {
                    resolve({ title: results[0].result, url: matchedTab.url, id: matchedTab.id });
                } else {
                    reject(new Error("Failed to get tab title."));
                }
            });
        });
    });
    

    }

    async function injectContentScript(tabId, initiator) { return new Promise((resolve, reject) => { chrome.scripting.executeScript({ target: { tabId: tabId }, files: ['content-script.js'] }, () => { if (chrome.runtime.lastError) { reject(chrome.runtime.lastError); } else { // Send initiator information to content script chrome.tabs.sendMessage(tabId, { action: "setInitiator", initiator: initiator }).catch(err => { console.warn("Tab might have closed before message could be sent:", err); //This is not critical }); resolve(); //Resolve after injection, not after analysis } }); }); }

    async function getRecentHistory(count) { return new Promise((resolve) => { chrome.history.search({ text: '', maxResults: count * 3, // Fetch more to filter effectively startTime: Date.now() - (7 * 24 * 60 * 60 * 1000) // Last 7 days }, (historyItems) => { const filteredItems = historyItems .filter(item => !item.url.startsWith('chrome://') && !item.url.startsWith('edge://') && !item.url.startsWith('about:') && item.url !== 'about:blank') .slice(0, count);

            // Add tab ID for content analysis lookup
            const itemsWithIds = filteredItems.map(item => ({ ...item, id: `history-${String(item.visitId)}` })); //Unique ID
            resolve(itemsWithIds);
    
        });
    });
    

    }

    // UPDATED: In analyzeUrls, pass the URL and title as source for debug logging. async function analyzeUrls(url, referrer, tabInfo, historyItems, parsedConfigs) { const urls = [url, referrer]; if (tabInfo) { urls.push(tabInfo.url); } else { // Only add the last 3 history items' URLs urls.push(...historyItems.slice(0,MAX_HISTORY_ITEMS).map(item => item.url)); } const filteredUrls = urls.filter(Boolean);

    const titles = [];
    if (tabInfo) {
        titles.push(tabInfo.title);
    } else {
        // Only add the last 3 history items' titles
      titles.push(...historyItems.slice(0,MAX_HISTORY_ITEMS).map(item => item.title));
    }
    const filteredTitles = titles.filter(Boolean);
    const results = [];
    for (const config of parsedConfigs) {
        let urlMatchCount = 0;
        let titleMatchCount = 0;
        for (const urlToCheck of filteredUrls) {
            const normalizedUrl = urlToCheck.toLowerCase();
              for (const keyword of config.keywordList) {
                if (normalizedUrl.includes(keyword)) {
                    console.debug(`Match found: Keyword "${keyword}" found in url: ${urlToCheck} (direct match)`);
                    urlMatchCount++;
                    break; // Only count each URL once per config
                }
            }
        }
        for (const titleToCheck of filteredTitles) {
            const normalizedTitle = titleToCheck.toLowerCase();
            for (const keyword of config.keywordList) {
                if (normalizedTitle.includes(keyword)) {
                     console.debug(`Match found: Keyword "${keyword}" found in title: ${titleToCheck} (direct match)`);
                    titleMatchCount++;
                    // Count all title matches per keyword
                }
            }
        }
        const urlMatchPercentage = filteredUrls.length > 0 ? Math.min(100, (urlMatchCount / filteredUrls.length) * 100) : 0;
        const titleMatchPercentage = filteredTitles.length > 0 ? Math.min(100, (titleMatchCount / (filteredTitles.length * config.keywordList.length)) * 100) : 0;
        console.log(`Match Percentage for ${config.name} - URLs:  ${urlMatchPercentage}% (Match Count: ${urlMatchCount}, URLs Checked: ${filteredUrls.length}), Titles: ${titleMatchPercentage}% (Match Count: ${titleMatchCount}, Titles Checked: ${filteredTitles.length})`);
        results.push({
            name: config.name,
            downloadPath: config.downloadPath,
            urlMatchPercentage,
            urlMatchCount,
            titleMatchPercentage,
            titleMatchCount,
            matchPercentage: Math.max(urlMatchPercentage, titleMatchPercentage),
            contentMatchPercentage: 0
        });
    }
    return results;
    

    }

    // Recursive function to traverse the DOM and check for keywords. function traverseAndCheck(node, keywordList, source, matchCounts) { if (!node) { return; }

    // Check the node's text content (if it's a text node).
    if (node.nodeType === Node.TEXT_NODE) {
        const normalizedText = node.textContent.toLowerCase();
        for (const keyword of keywordList) {
            if (normalizedText.includes(keyword)) {
                 console.debug(`Match found: Keyword "${keyword}" found in ${source} text content`);
                matchCounts.totalContentMatches++;
                matchCounts.matchingItemsCount = 1; //Mark as matched
            }
        }
    }
    
    // Check element attributes (if it's an element node).
    if (node.nodeType === Node.ELEMENT_NODE) {
        for (const attr of node.attributes) {
            const normalizedAttrValue = attr.value.toLowerCase();
            for (const keyword of keywordList) {
                if (normalizedAttrValue.includes(keyword)) {
                    console.debug(`Match found: Keyword "${keyword}" found in ${source} attribute ${attr.name}`);
                    matchCounts.totalContentMatches++;
                    matchCounts.matchingItemsCount = 1;//Mark as matched
                }
            }
        }
    }
    
    // Recursively check child nodes.
    for (const child of node.childNodes) {
        traverseAndCheck(child, keywordList, source, matchCounts);
    }
    

    }

    // UPDATED: analyzePageContent now uses traverseAndCheck async function analyzePageContent(items, parsedConfigs) { const results = []; for (const config of parsedConfigs) { let totalContentMatches = 0; let matchingItemsCount = 0; // Number of items that had at least one match

        for (const item of items) {
           if(!item.doc) continue; //Skip if no doc
    
            const matchCounts = { totalContentMatches: 0, matchingItemsCount: 0 }; //Counts per item
    
            traverseAndCheck(item.doc.documentElement, config.keywordList, `content from item with title: ${item.title}`, matchCounts);
            totalContentMatches += matchCounts.totalContentMatches;
            if(matchCounts.matchingItemsCount > 0) matchingItemsCount++; //Increment if any matches were found
        }
    
    
        const contentMatchPercentage = items.length > 0 ? Math.min(100, (matchingItemsCount / items.length) * 100) : 0;
        results.push({
            name: config.name,
            downloadPath: config.downloadPath,
            contentMatchPercentage,
            contentMatchCount: totalContentMatches,
            matchPercentage: contentMatchPercentage,
            urlMatchPercentage: 0,
            titleMatchPercentage: 0,
            filenameMatchPercentage: 0
        });
    }
    return results;
    

    }

    function showDownloadPathNotification(downloadItem, options) { if (options.length > 0 && (options[0].matchPercentage >= MATCH_THRESHOLD)) { // No notification if a high match. processDownloadChoice(downloadItem.id, 0); return; }

    try {
        chrome.notifications.create({
            type: 'basic',
            iconUrl: 'icons/icon48.png',
            title: 'Choose Download Location',
            message: `Where would you like to save "${downloadItem.filename.split('/').pop()}"?`,
            buttons: [
                ...(options.length > 0 ? [{ title: `${options[0].name} (${Math.round(options[0].matchPercentage)}%)` }] : []), // Use overall matchPercentage in notification buttons
                ...(options.length > 1 ? [{ title: `${options[1].name} (${Math.round(options[1].matchPercentage)}%)` }] : []),
                { title: 'Use Default Folder' }
            ],
            requireInteraction: true
        }, (notificationId) => {
            if (chrome.runtime.lastError) {
                console.error("Error creating notification:", chrome.runtime.lastError.message);
                processDownloadChoice(downloadItem.id, null); // Fallback
                return;
            }
            downloadNotifications.set(notificationId, { downloadId: downloadItem.id, options });
            setTimeout(() => {
                try {
                    chrome.notifications.clear(notificationId, () => {
                        if (chrome.runtime.lastError) { console.log("Notification already closed:", chrome.runtime.lastError.message); }
                        const notificationInfo = downloadNotifications.get(notificationId);
                        if (notificationInfo) { processDownloadChoice(notificationInfo.downloadId, null); downloadNotifications.delete(notificationId); }
                    });
                } catch (error) { console.error("Error clearing notification:", error); }
            }, NOTIFICATION_TIMEOUT);
        });
    } catch (error) {
        console.error("Error showing notification:", error);
        processDownloadChoice(downloadItem.id, null); // Fallback to default
    }
    

    }

    async function processDownloadChoice(downloadId, chosenIndex) { const pendingDownload = pendingDownloads.get(downloadId); if (!pendingDownload) { console.log(Pending download with ID ${downloadId} not found.); return; }

    const { downloadItem, suggest } = pendingDownload;
    const matchResults = (await analyzeDownload(downloadItem, (await chrome.storage.sync.get('gameConfigs')).gameConfigs));
    pendingDownloads.delete(downloadId); // Moved up here
    
    if (chosenIndex === null || chosenIndex === undefined || !matchResults) {
        console.log(`ProcessDownloadChoice:  Default location chosen.`);
        callSuggestSafely(downloadId, {});
    } else if (matchResults[chosenIndex]) {
        const chosen = matchResults[chosenIndex];
        console.log(`ProcessDownloadChoice:  User chose option ${chosenIndex}: ${chosen.name}`);
        const suggestedFilename = getSuggestedFilename(downloadItem, chosen);
        callSuggestSafely(downloadId, { filename: suggestedFilename, conflictAction: 'uniquify' });
    } else {
        console.log(`ProcessDownloadChoice:  Invalid chosenIndex ${chosenIndex} or matchResults missing.`);
        callSuggestSafely(downloadId, {});
    }
    

    }

    chrome.notifications.onButtonClicked.addListener((notificationId, buttonIndex) => { const notificationInfo = downloadNotifications.get(notificationId); if (!notificationInfo) { return; }

    // Handle button clicks: 0 and 1 are custom options, 2 is "Use Default"
    if (buttonIndex === 2) {
        processDownloadChoice(notificationInfo.downloadId, null); // Default
    } else {
        processDownloadChoice(notificationInfo.downloadId, buttonIndex); // Custom choice
    }
    
    try {
        chrome.notifications.clear(notificationId, () => {
            if (chrome.runtime.lastError) { console.log("Notification already closed:", chrome.runtime.lastError.message); }
            downloadNotifications.delete(notificationId); // Clean up
        });
    } catch (error) { console.error("Error clearing notification:", error); }
    

    });

    chrome.notifications.onClicked.addListener((notificationId) => { const notificationInfo = downloadNotifications.get(notificationId); if (!notificationInfo) { return; } processDownloadChoice(notificationInfo.downloadId, null); // Treat click as "Use Default" chrome.notifications.clear(notificationId, () => { if (chrome.runtime.lastError) { console.log("Notification already closed:", chrome.runtime.lastError.message); } downloadNotifications.delete(notificationId); }); });

    chrome.notifications.onClosed.addListener((notificationId) => { const notificationInfo = downloadNotifications.get(notificationId); if (!notificationInfo) { return; } processDownloadChoice(notificationInfo.downloadId, null); downloadNotifications.delete(notificationId); });

    // content-script.js // Content script to analyze page content for game-related keywords

    (function() { // Extract text content from the page function extractPageContent() { // Get all text from relevant elements, avoiding scripts and styles const elements = document.querySelectorAll('p, h1, h2, h3, h4, h5, h6, a, li, span, div, td, th'); // Added table elements let textContent = '';

      elements.forEach(element => {
          // Skip hidden elements
          if (element.offsetParent === null) return;
    
          // Get text and remove extra whitespace
          const text = element.textContent.trim();
          if (text) {
              textContent += ' ' + text;
          }
      });
    
      // Clean up the text (remove excessive whitespace)
      textContent = textContent.replace(/\s+/g, ' ').trim();
    
      // Get page title as well
      const pageTitle = document.title;
    
      return {
          text: textContent,
          title: pageTitle
      };
    

    }

    // Receive initiator and send content analysis chrome.runtime.onMessage.addListener((message, sender, sendResponse) => { if (message.action === "setInitiator") { const pageContent = extractPageContent(); chrome.runtime.sendMessage({ action: "contentAnalysis", content: pageContent.title + ' ' + pageContent.text, initiator: message.initiator // Pass initiator for identification }); } }); })();

    Para resolver esse problema e melhorar a implementação, sugiro o seguinte:

    Revise a lógica da função de análise recursiva para garantir que ela esteja percorrendo corretamente todas as subpáginas e elementos dentro das 3 páginas principais. Verifique se a extração do texto de cada página está sendo feita de forma adequada, considerando diferentes elementos HTML que possam conter texto relevante, como parágrafos, cabeçalhos, listas, etc. Aperfeiçoe o algoritmo de busca das palavras-chave, levando em consideração possíveis variações de capitalização, pontuação e espaçamento. Utilize expressões regulares para uma busca mais flexível e abrangente. Certifique-se de que o cálculo da porcentagem de cobertura esteja correto, dividindo o número de ocorrências da palavra-chave pelo total de palavras na página e multiplicando por 100. Considere implementar um sistema de cache para armazenar os resultados da análise de cada página, evitando processamento desnecessário em chamadas subsequentes para a mesma página. Realize testes extensivos com diferentes páginas e palavras-chave para garantir que a análise recursiva esteja funcionando corretamente e fornecendo resultados precisos. Ao seguir essas etapas, você poderá corrigir os problemas existentes na análise recursiva do conteúdo das páginas e obter resultados mais precisos e confiáveis na busca por palavras-chave e cálculo da porcentagem de cobertura. o funcionamento dele ser muito semelhante com o do notification no quesito de analise

  2. Perplexity Assistant

    Based on your description, it seems you're looking to improve the content analysis functionality in your Chrome extension. The content script you've provided is a good start, but there are several ways to enhance its effectiveness and accuracy. Here's an improved version of the content script that addresses some of the issues you've mentioned:

    // content-script.js
    (function() {
        // Function to extract text content from an element
        function extractTextFromElement(element) {
            if (element.tagName === 'SCRIPT' || element.tagName === 'STYLE') {
                return '';
            }
            if (element.childNodes.length === 0) {
                return element.textContent.trim();
            }
            let text = '';
            for (let child of element.childNodes) {
                text += extractTextFromElement(child) + ' ';
            }
            return text.trim();
        }
    
        // Function to extract all text content from the page
        function extractPageContent() {
            const body = document.body;
            let textContent = extractTextFromElement(body);
            
            // Clean up the text (remove excessive whitespace)
            textContent = textContent.replace(/\s+/g, ' ').trim();
    
            // Get page title
            const pageTitle = document.title;
    
            // Get meta description
            const metaDescription = document.querySelector('meta[name="description"]');
            const description = metaDescription ? metaDescription.getAttribute('content') : '';
    
            // Get all link texts
            const linkTexts = Array.from(document.links).map(link =&gt; link.textContent.trim()).join(' ');
    
            return {
                text: textContent,
                title: pageTitle,
                description: description,
                links: linkTexts
            };
        }
    
        // Function to analyze content for keywords
        function analyzeContent(content, keywords) {
            const normalizedContent = content.toLowerCase();
            const wordCount = normalizedContent.split(/\s+/).length;
    
            const results = {};
            for (let keyword of keywords) {
                const regex = new RegExp(`\\b${keyword.toLowerCase()}\\b`, 'gi');
                const matches = normalizedContent.match(regex) || [];
                const occurrences = matches.length;
                const coverage = (occurrences / wordCount) * 100;
                results[keyword] = {
                    occurrences: occurrences,
                    coverage: coverage.toFixed(2)
                };
            }
    
            return results;
        }
    
        // Listen for messages from the background script
        chrome.runtime.onMessage.addListener((message, sender, sendResponse) =&gt; {
            if (message.action === "analyzeContent") {
                const pageContent = extractPageContent();
                const analysisResults = analyzeContent(
                    pageContent.title + ' ' + pageContent.description + ' ' + pageContent.text + ' ' + pageContent.links,
                    message.keywords
                );
    
                chrome.runtime.sendMessage({
                    action: "contentAnalysisResult",
                    results: analysisResults,
                    url: window.location.href,
                    title: pageContent.title
                });
            }
        });
    
        // Notify that the content script is ready
        chrome.runtime.sendMessage({ action: "contentScriptReady" });
    })();
    

    This improved content script addresses several key points:

    1. It uses a recursive function to extract text from all elements, avoiding scripts and styles.
    2. It includes the page title, meta description, and link texts in the analysis.
    3. It uses a more robust keyword matching system with regular expressions to account for word boundaries.
    4. It calculates the coverage percentage based on the number of occurrences divided by the total word count.

    To use this in your background script, you would need to modify your existing code. Here's an example of how you might integrate this:

    // In your background.js
    
    async function analyzePageContent(tab, keywords) {
        return new Promise((resolve, reject) =&gt; {
            chrome.tabs.sendMessage(tab.id, { action: "analyzeContent", keywords: keywords }, (response) =&gt; {
                if (chrome.runtime.lastError) {
                    reject(chrome.runtime.lastError);
                } else {
                    resolve(response);
                }
            });
        });
    }
    
    // Use this function in your existing analyzeDownload function
    async function analyzeDownload(downloadItem, gameConfigs) {
        // ... existing code ...
    
        // Analyze page content
        let contentResults = [];
        if (tabInfo) {
            try {
                const keywords = gameConfigs.flatMap(config =&gt; config.keywords.split(',').map(k =&gt; k.trim()));
                const analysisResults = await analyzePageContent(tabInfo, keywords);
                contentResults = processAnalysisResults(analysisResults, gameConfigs);
            } catch (error) {
                console.error("Error analyzing page content:", error);
            }
        }
    
        // ... rest of your existing code ...
    }
    
    function processAnalysisResults(analysisResults, gameConfigs) {
        return gameConfigs.map(config =&gt; {
            const keywordResults = config.keywords.split(',').map(keyword =&gt; {
                const result = analysisResults.results[keyword.trim()];
                return result ? parseFloat(result.coverage) : 0;
            });
            const averageCoverage = keywordResults.reduce((sum, coverage) =&gt; sum + coverage, 0) / keywordResults.length;
            return {
                name: config.name,
                downloadPath: config.downloadPath,
                contentMatchPercentage: averageCoverage,
                matchPercentage: averageCoverage,
                urlMatchPercentage: 0,
                titleMatchPercentage: 0,
                filenameMatchPercentage: 0
            };
        });
    }
    

    This implementation should provide more accurate and comprehensive content analysis. It analyzes the entire page content, including title, description, and links, and provides a coverage percentage for each keyword. The results are then processed to fit into your existing structure.

    Remember to update your manifest.json to include the content script:

    {
      "content_scripts": [
        {
          "matches": ["<all_urls>"],
          "js": ["content-script.js"],
          "run_at": "document_idle"
        }
      ]
    }
    

    This approach should give you results more similar to your notification analysis, as it's analyzing the full page content in a more thorough manner.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.

Identical first prompt