This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
AI Multi-Chat Assistant is a Chrome Extension (Manifest V3) that enables simultaneous chatting with 4 AI platforms: Grok, Gemini, Claude, and ChatGPT. The extension displays all four platforms side-by-side in iframes, allows unified input, and coordinates question submission across all platforms.
Language Context: This is a bilingual project (Chinese/English). Code comments are primarily in Chinese, while technical elements use English conventions.
- Navigate to
chrome://extensions/ - Enable "Developer mode" (top right)
- Click "Load unpacked"
- Select the
chrome-extensiondirectory
- For manifest.json, background.js, or content scripts changes:
- Click reload button in
chrome://extensions/for this extension
- Click reload button in
- For popup.html, popup.js, popup.css:
- Close and reopen the extension popup (changes apply immediately)
- Background Service Worker:
chrome://extensions/→ Click "service worker" link under extension - Popup Page: Right-click extension icon → "Inspect popup"
- Content Scripts in iframes: Open extension → Right-click iframe → "Inspect"
All debugging logs are prefixed with [platform-name] or [AI Multi-Chat] for easy filtering.
popup.js (Main Controller)
↓ postMessage({type: 'AI_SUBMIT_QUESTION'})
iframe (e.g., grok.com)
↓ Received by content script
injection-core.js (submitQuestion)
↓ DOM manipulation: fillQuestion() → clickButton()
AI Website
↓ Network request intercepted
injection-core.js (setupFetchMonitor/setupXHRMonitor)
↓ postMessage({type: 'AI_RESPONSE_RECEIVED'})
popup.js (handleMessage)
↓ updateStatus()
UI Status Indicator
Layer 1: Extension Infrastructure
manifest.json: Chrome extension configuration, permissions, content script injection rulesbackground.js: Service worker (currently minimal, reserved for future features)rules.json: declarativeNetRequest rules to remove security headers (X-Frame-Options, CSP)
Layer 2: Main UI Controller
popup.html/css/js: Main extension page, 4-iframe layout, unified input control, message routing
Layer 3: Platform Injection System
platforms-config.js: Platform-specific configurations (selectors, API patterns, response parsers)injection-core.js: Core injection logic (network monitoring, DOM automation, retry mechanisms){platform}-script.js: Platform-specific initialization (Grok, Gemini, Claude, ChatGPT)google-oauth-handler.js: OAuth detection and login flow handling
1. Platform Configuration System
Each platform in PLATFORM_CONFIGS defines:
detectTextarea(): Function to detect if input field is readydetectButton(): Function to detect if submit button is ready (with anti-spam logic)fillQuestion(q): Function to fill question into input fieldclickButton(): Function to click submit buttonresponseType: 'fetch_stream' or 'xhr_stream' (determines which monitor to use)responseApiPattern: URL pattern to interceptparseResponse(rawText): Platform-specific response parser
2. Network Interception Strategy
- Fetch API Interception (Grok, Claude, ChatGPT): Overwrites
window.fetchto intercept streaming responses - XMLHttpRequest Interception (Gemini): Hooks into
XMLHttpRequest.prototype.open/sendfor XHR-based APIs - Both approaches clone response streams to avoid breaking original functionality
3. Retry Mechanism with Intelligent Waiting
Instead of fixed delays, submitQuestion() uses intelligent polling:
- Wait for textarea (max 30 retries × 1s)
- Fill question immediately when textarea ready
- Poll for button availability (max 30 retries × 1s)
- Click button as soon as it's enabled (no fixed wait after fill)
This design minimizes submission latency while handling dynamic UI states.
4. OAuth Login Flow Handling
- Grok: Manual guided flow - detects login need, shows overlay with instructions, opens new tab
- ChatGPT: Automatic flow - detects login need, auto-opens popup window, auto-reloads iframe when closed
- Gemini/Claude: User handles login directly in iframe (no automation)
Detection happens in platform-specific scripts by monitoring URL patterns (e.g., accounts.x.ai, auth.openai.com).
5. Message Protocol
All iframe ↔ popup communication uses postMessage with typed messages:
AI_SUBMIT_QUESTION: popup → content script (initiate question submission)AI_QUESTION_SENT: content script → popup (question sent successfully)AI_RESPONSE_START: content script → popup (response streaming started)AI_RESPONSE_RECEIVED: content script → popup (complete response parsed)AI_ERROR: content script → popup (error occurred)AI_URL_CHANGED: content script → popup (URL changed, save to localStorage)AI_NEW_CHAT: popup → content script (reset to new conversation)
rules.json uses Chrome's declarativeNetRequest API to remove iframe-blocking headers. This is necessary because all four AI platforms set X-Frame-Options or CSP headers that prevent iframe embedding. Rules also modify Referer and Origin headers for Gemini to bypass additional restrictions.
Grok's UI reuses the same button for "Send" and "Stop generating". detectButton() explicitly checks for stop button presence:
const stopBtn = document.querySelector('button[aria-label*="Stop"]');
if (stopBtn) return false; // Don't allow submission while generatingThis prevents accidentally clicking "Stop" when trying to submit a new question.
Each platform has different API response formats:
- Grok: Newline-delimited JSON with
result.tokenstreaming - Gemini: Nested JSON array with path
outer[0][2] → inner[4][0][1] - Claude: Full response object with
chat_messagesarray, recursively extracts alltextfields - ChatGPT: Server-sent events format with
data: {...}lines
See parseResponse() in platforms-config.js for platform-specific parsing logic.
injection-core.js intercepts History API (pushState, replaceState) and browser events (popstate, hashchange) to track URL changes. When URLs change (e.g., new conversation started), they're saved to localStorage and restored on next extension open. This maintains conversation continuity across sessions.
All content scripts use "run_at": "document_start" and "all_frames": true to ensure:
- Scripts run before page JavaScript executes (necessary for fetch/XHR interception)
- Scripts run in both main frames and nested iframes (handles OAuth flows)
The unified input box in popup.js is draggable to avoid blocking iframe content. Uses pointer events with pointer capture for reliable dragging (handles fast mouse movement and dragging over iframes). Position is saved to localStorage.
- Add platform configuration to
PLATFORM_CONFIGSinplatforms-config.js - Create platform-specific script
{platform}-script.js(follow existing patterns) - Add content script entry in
manifest.json - Add host permission in
manifest.json - Add header removal rule in
rules.json - Add platform to
platformsarray inpopup.js - Add iframe HTML in
popup.html
- Inspect the AI platform's new DOM structure
- Update selector functions in
platforms-config.js:detectTextarea(): Find new input field selectordetectButton(): Find new submit button selector- Update
fillQuestion()andclickButton()if interaction method changed
- Open browser DevTools on the AI platform
- Submit a question and observe Network tab
- Identify the API endpoint that returns responses
- Update
responseApiPatternandparseResponse()inplatforms-config.js
Edit platform-specific script (e.g., grok-script.js, chatgpt-script.js):
- Update URL pattern detection in
window.addEventListener('load') - Modify login detection logic and UI overlay
- Update message types sent to popup
- Adjust popup message handler in
handleLoginMessage()
AI platforms frequently update their UIs and APIs. Test these areas after updates:
- Input field detection (can extension find the textarea?)
- Button detection (can extension find and click send button?)
- Response interception (is the API endpoint still the same?)
- Response parsing (has the response format changed?)
This extension uses Manifest V3 and Chrome-specific APIs. It will NOT work in Firefox without modifications. Key Chrome-specific features:
declarativeNetRequest(header modification)chrome.tabsAPI (login flow)- Manifest V3 service worker
The extension modifies security headers to enable iframe embedding. This is necessary for functionality but reduces security isolation. Users should only use this extension with trusted AI platforms and understand the security trade-offs.
-
OAuth in iframes: Some platforms require OAuth login which cannot complete in iframes. The extension provides workarounds (new tab/window) but this is inherently limited by browser security.
-
Dynamic UI Changes: AI platforms frequently update their UIs. Selector-based automation is fragile and requires maintenance when platforms update.
-
Rate Limiting: Sending questions to all 4 platforms simultaneously may trigger rate limits on some platforms.
-
Response Display: Currently, the extension only shows status indicators. Displaying full responses inline would require additional UI implementation.
-
Cloudflare/Bot Detection: Some platforms may show Cloudflare verification or bot detection when loaded in iframes. User must complete verification manually in iframe.