No chat to show

This project's files are all here to explore.

Files
background.js
content.css
content.js
manifest.json
popup.html
popup.js
Code
6 841
content.js
let API_KEY = '';
let SELECTED_MODEL = 'gemini-3-flash-preview';
let autoSolveEnabled = false;
let solutionPanel = null;

chrome.storage.local.get(['geminiApiKey', 'autoSolve', 'selectedModel'], (result) => {
  API_KEY = result.geminiApiKey || '';
  autoSolveEnabled = result.autoSolve || false;
  SELECTED_MODEL = result.selectedModel || 'gemini-3-flash-preview';
  if (autoSolveEnabled) {
    startAutoSolve();
  }
});

chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  if (message.action === 'solveCurrent') {
    solveCurrentQuestion();
    sendResponse({ success: true });
  } else if (message.action === 'toggleAutoSolve') {
    autoSolveEnabled = message.enabled;
    if (autoSolveEnabled) {
      startAutoSolve();
    }
    sendResponse({ success: true });
  } else if (message.action === 'solveNext') {
    handleNextQuestion();
    sendResponse({ success: true });
  }
  return true;
});

function extractQuestionFromPage() {
  const questionElements = document.querySelectorAll('.question-text, [class*="question"], [class*="Question"]');
  let questionText = '';
  
  for (const elem of questionElements) {
    const text = elem.innerText || elem.textContent;
    if (text && text.length > 10) {
      questionText += text + '\n';
    }
  }
  
  if (!questionText) {
    const bodyText = document.body.innerText;
    const lines = bodyText.split('\n').filter(line => line.trim().length > 0);
    questionText = lines.slice(0, 20).join('\n');
  }
  
  return questionText.trim();
}

async function solveWithGemini(questionText) {
  if (!API_KEY) {
    throw new Error('No API key configured. Click the extension icon to set up your key.');
  }

  const storage = await chrome.storage.local.get(['selectedModel']);
  SELECTED_MODEL = storage.selectedModel || 'gemini-3-flash-preview';

  const apiUrl = `https://generativelanguage.googleapis.com/v1beta/models/${SELECTED_MODEL}:generateContent?key=${API_KEY}`;
  
  const prompt = `You are a helpful math tutor. Solve this Sparx Maths question step by step. Provide a clear, detailed explanation and the final answer.

Question: ${questionText}

Provide your answer in this format:
**Solution:**
[Step-by-step explanation]

**Final Answer:** [Clear answer]`;

  try {
    const response = await fetch(apiUrl, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        contents: [{
          parts: [{
            text: prompt
          }]
        }],
        generationConfig: {
          temperature: 0.4,
          topK: 32,
          topP: 1,
          maxOutputTokens: 2048
        }
      })
    });

    const data = await response.json();

    if (!response.ok) {
      console.error('Full API Error Response:', data);
      
      const errorMessage = data.error?.message || JSON.stringify(data);
      throw new Error(`Gemini API Error (${response.status}): ${errorMessage}`);
    }
    
    if (data.candidates && data.candidates[0] && data.candidates[0].content) {
      return data.candidates[0].content.parts[0].text;
    } else {
      console.error('Unexpected API response structure:', data);
      throw new Error('Invalid API response format: ' + JSON.stringify(data).substring(0, 200));
    }
  } catch (error) {
    console.error('Gemini API error:', error);
    throw error;
  }
}

function createSolutionPanel() {
  if (solutionPanel) {
    solutionPanel.remove();
  }
  
  solutionPanel = document.createElement('div');
  solutionPanel.className = 'sparx-ai-solution-panel';
  solutionPanel.innerHTML = `
    <div class="sparx-ai-header">
      <span class="sparx-ai-title">๐Ÿค– AI Solution</span>
      <button class="sparx-ai-close">โœ•</button>
    </div>
    <div class="sparx-ai-content">
      <div class="sparx-ai-loading">Thinking...</div>
    </div>
  `;
  
  document.body.appendChild(solutionPanel);
  
  solutionPanel.querySelector('.sparx-ai-close').addEventListener('click', () => {
    solutionPanel.remove();
  });
  
  return solutionPanel;
}

function displaySolution(solutionText) {
  const content = solutionPanel.querySelector('.sparx-ai-content');
  content.innerHTML = `
    <div class="sparx-ai-text">${formatSolution(solutionText)}</div>
    <button class="sparx-ai-next-btn">Next Question โžœ</button>
  `;
  
  const nextBtn = content.querySelector('.sparx-ai-next-btn');
  nextBtn.addEventListener('click', () => {
    console.log('Next button clicked in solution panel');
    handleNextQuestion();
  });
}

function formatSolution(text) {
  return text
    .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
    .replace(/\n\n/g, '</p><p>')
    .replace(/\n/g, '<br>')
    .replace(/^/, '<p>')
    .replace(/$/, '</p>');
}

function handleNextQuestion() {
  console.log('Attempting to find next button...');
  
  const allButtons = document.querySelectorAll('button, a, input[type="button"], input[type="submit"], [role="button"]');
  console.log(`Found ${allButtons.length} total clickable elements`);
  
  let clicked = false;
  let foundButtons = [];
  
  for (const btn of allButtons) {
    const text = (btn.innerText || btn.textContent || btn.value || btn.getAttribute('aria-label') || '').toLowerCase().trim();
    const classes = btn.className.toLowerCase();
    const id = (btn.id || '').toLowerCase();
    
    foundButtons.push({ element: btn, text, classes, id });
    
    if (text.includes('next') || 
        text.includes('continue') || 
        text.includes('forward') ||
        text === 'โ†’' || 
        text === 'ยป' ||
        text === '>' ||
        classes.includes('next') ||
        classes.includes('continue') ||
        classes.includes('forward') ||
        id.includes('next') ||
        id.includes('continue')) {
      
      console.log('Found potential next button:', { text, classes, id, html: btn.outerHTML.substring(0, 200) });
      
      if (btn.disabled || btn.hasAttribute('disabled') || btn.classList.contains('disabled')) {
        console.log('Button is disabled, skipping');
        continue;
      }
      
      console.log('Clicking next button!');
      btn.click();
      clicked = true;