/** * iframe Fetch Client - Simplified Implementation * Implements JSON-RPC 2.0 messaging protocol per MESSAGING_PROTOCOL.md */ // JSON-RPC Client for communication with parent class JSONRPCClient { constructor() { this.requestId = 0; this.pendingRequests = new Map(); this.setupMessageListener(); } setupMessageListener() { window.addEventListener("message", (event) => { const message = event.data; // Check if this is a response to our own request or a ServiceWorker request if (message.jsonrpc === "2.0" && message.id !== undefined) { if (this.pendingRequests.has(message.id)) { this.handleResponse(message); } else { // This is a response to a ServiceWorker request, relay it back this.relayToServiceWorker(message); } } }); } relayToServiceWorker(response) { // Forward the JSON-RPC response to ServiceWorker if (navigator.serviceWorker.controller) { navigator.serviceWorker.controller.postMessage(response); } } async fetch(request) { const id = ++this.requestId; return new Promise((resolve, reject) => { this.pendingRequests.set(id, { resolve, reject }); // Send JSON-RPC request to parent window.parent.postMessage({ jsonrpc: "2.0", method: "fetch", params: { request }, id, }, "*"); // Timeout after 10 seconds setTimeout(() => { if (this.pendingRequests.has(id)) { this.pendingRequests.delete(id); reject(new Error(`Timeout fetching: ${request.url}`)); } }, 10000); }); } handleResponse(message) { const { id, result, error } = message; const pending = this.pendingRequests.get(id); if (!pending) return; this.pendingRequests.delete(id); if (error) { pending.reject(new Error(`${error.message} (code: ${error.code})`)); } else { pending.resolve(result); } } } // Console Interceptor - forwards console messages to parent class ConsoleInterceptor { constructor() { this.originalConsole = {}; this.methods = ['log', 'warn', 'error', 'info', 'debug']; this.init(); } init() { // Store original methods and override in single pass this.methods.forEach((method) => { if (typeof console[method] === 'function') { this.originalConsole[method] = console[method]; console[method] = (...args) => { // Call original method try { this.originalConsole[method](...args); } catch (e) { // Continue if original fails } // Send to parent this.sendConsoleMessage(method, ...args); }; } }); } sendConsoleMessage(level, ...args) { const message = args.map((arg) => { if (arg === undefined) return 'undefined'; if (arg === null) return 'null'; if (typeof arg === 'object') { try { return JSON.stringify(arg, (key, value) => { if (value instanceof Error) { return { name: value.name, message: value.message, stack: value.stack }; } return value; }); } catch { return String(arg); } } return String(arg); }).join(' '); try { window.parent.postMessage({ jsonrpc: "2.0", method: "console", params: { level, message } }, "*"); } catch (error) { // Retry once after delay if postMessage fails setTimeout(() => { try { window.parent.postMessage({ jsonrpc: "2.0", method: "console", params: { level: "error", message: `[DELAYED] ${message}` } }, "*"); } catch { // Give up if retry fails } }, 100); } } } // Navigation Handler - manages iframe navigation and history class NavigationHandler { constructor() { this.historyIndex = 0; // Track current position in history this.historyLength = 1; // Track total history length this.currentSemanticPath = '/'; // Always start with root path for SPAs this.setupMessageListener(); this.setupHistoryListeners(); this.overrideHistoryMethods(); this.updateNavigationState(); } setupMessageListener() { window.addEventListener("message", (event) => { const message = event.data; if (message.jsonrpc === "2.0") { switch (message.method) { case "navigate": this.handleNavigate(message.params.url); break; case "refresh": this.handleRefresh(); break; case "goBack": this.handleGoBack(); break; case "goForward": this.handleGoForward(); break; } } }); } setupHistoryListeners() { // Listen for popstate events (back/forward navigation) window.addEventListener('popstate', (event) => { // When user navigates (back or forward), we need to update our tracking // The state object can help us determine our position // Update current semantic path based on actual URL this.currentSemanticPath = window.location.pathname + window.location.search + window.location.hash; this.updateNavigationState(); }); // Listen for hash changes window.addEventListener('hashchange', () => { this.currentSemanticPath = window.location.pathname + window.location.search + window.location.hash; this.updateNavigationState(); }); } overrideHistoryMethods() { // Override history.pushState and history.replaceState to detect SPA navigation this.originalPushState = window.history.pushState; this.originalReplaceState = window.history.replaceState; window.history.pushState = (...args) => { const result = this.originalPushState.apply(window.history, args); // Extract semantic path from the URL argument or current location let semanticPath; if (args[2] && typeof args[2] === 'string') { // If URL is provided as third argument, use it try { const url = new URL(args[2], window.location.origin); semanticPath = url.pathname + url.search + url.hash; } catch { semanticPath = window.location.pathname + window.location.search + window.location.hash; } } else { // Otherwise use current location semanticPath = window.location.pathname + window.location.search + window.location.hash; } // pushState was called, update semantic path this.currentSemanticPath = semanticPath; this.updateNavigationState(); return result; }; window.history.replaceState = (...args) => { const result = this.originalReplaceState.apply(window.history, args); // Extract semantic path for replaceState as well let semanticPath; if (args[2] && typeof args[2] === 'string') { try { const url = new URL(args[2], window.location.origin); semanticPath = url.pathname + url.search + url.hash; } catch { semanticPath = window.location.pathname + window.location.search + window.location.hash; } } else { semanticPath = window.location.pathname + window.location.search + window.location.hash; } // replaceState was called, update semantic path this.currentSemanticPath = semanticPath; this.updateNavigationState(); return result; }; } handleNavigate(url) { try { // Validate URL - must be same origin const targetUrl = new URL(url, window.location.origin); if (targetUrl.origin !== window.location.origin) { console.error('Navigation to different origin not allowed:', url); return; } // Extract the semantic path (pathname + search + hash) const semanticPath = targetUrl.pathname + targetUrl.search + targetUrl.hash; // Use browser's history API to trigger SPA navigation // This triggers SPA router navigation the semantic path to the parent for display // The SPA's router will handle the navigation internally // Use history.pushState to trigger SPA navigation this.currentSemanticPath = semanticPath; this.updateNavigationState(); // Use browser's history.pushState to trigger SPA navigation the SPA of the navigation intent // This is what most SPAs (React Router, Vue Router, etc.) listen for window.history.pushState({}, '', semanticPath); // URL change - Many SPAs listen for popstate events window.dispatchEvent(new PopStateEvent('popstate', { state: {} })); // Update navigation state to parent } catch (error) { console.error('Invalid navigation URL:', url, error); } } handleRefresh() { // Reload the iframe by going back to base URL and then reloading // This prevents trying to fetch non-existent SPA routes window.location.replace('/'); } handleGoBack() { if (this.historyIndex > 0) { window.history.back(); } } handleGoForward() { if (this.historyIndex < this.historyLength - 1) { window.history.forward(); } } updateNavigationState() { // Use tracked semantic path instead of window.location // This allows iframe to stay on base URL while showing semantic paths const semanticPath = this.currentSemanticPath || (window.location.pathname + window.location.search + window.location.hash); const state = { currentUrl: semanticPath, canGoBack: false, // Let parent handle history tracking canGoForward: false // Let parent handle history tracking }; // Send navigation state to parent try { window.parent.postMessage({ jsonrpc: "2.0", method: "updateNavigationState", params: state }, "*"); } catch (error) { console.error('Failed to send navigation state:', error); } } } // Main Fetch Client class FetchClient { constructor() { this.rpcClient = new JSONRPCClient(); this.consoleInterceptor = new ConsoleInterceptor(); this.navigationHandler = new NavigationHandler(); this.init(); } async init() { try { await this.setupServiceWorker(); await this.loadSiteIndex(); } catch (error) { this.showError("Failed to initialize fetch client", error); } } async setupServiceWorker() { if (!("serviceWorker" in navigator)) { throw new Error("ServiceWorker not supported"); } // Check if already registered const existing = await navigator.serviceWorker.getRegistration(); if (existing) { console.log("ServiceWorker already registered"); this.setupServiceWorkerCommunication(); return; } // Register new ServiceWorker const registration = await navigator.serviceWorker.register("/sw.js", { scope: "/" }); console.log("ServiceWorker registered:", registration); await navigator.serviceWorker.ready; this.setupServiceWorkerCommunication(); this.blockFutureRegistrations(); // Block future registrations to prevent site from registering its own SW } setupServiceWorkerCommunication() { // Relay JSON-RPC requests from ServiceWorker to parent navigator.serviceWorker.addEventListener("message", (event) => { const { data } = event; if (data.jsonrpc === "2.0" && data.method && data.id !== undefined) { window.parent.postMessage(data, "*"); } }); } blockFutureRegistrations() { navigator.serviceWorker.register = () => { console.log("Blocked ServiceWorker registration attempt"); return Promise.resolve({ scope: "/", active: navigator.serviceWorker.controller, installing: null, waiting: null, addEventListener: () => {}, removeEventListener: () => {}, }); }; } async loadSiteIndex() { const serializedRequest = { url: `${location.origin}/`, method: "GET", body: null, headers: {}, }; const response = await this.rpcClient.fetch(serializedRequest); if (response?.status !== 200) { throw new Error(`Failed to fetch site index: ${response?.status || 'Invalid response from site: ' + response} ${response?.statusText || ''}`); } if (response.headers["Content-Type"] !== "text/html") { throw new Error(`Unexpected Content-Type: ${response.headers["Content-Type"]}`); } const bytes = new Uint8Array(atob(response.body).split('').map(c => c.charCodeAt(0))); const text = new TextDecoder().decode(bytes); this.replaceDocument(text); } replaceDocument(htmlContent) { // Create a new document from the HTML content const parser = new DOMParser(); const newDoc = parser.parseFromString(htmlContent, "text/html"); // Extract scripts for re-execution const scripts = []; newDoc.querySelectorAll("script").forEach((script) => { scripts.push({ src: script.src, type: script.type, async: script.hasAttribute("async"), defer: script.hasAttribute("defer"), }); script.remove(); }); // Replace document content document.head.innerHTML = newDoc.head.innerHTML; document.body.innerHTML = newDoc.body.innerHTML; // Re-add scripts to execute them scripts.forEach((script) => { const newScript = document.createElement("script"); newScript.src = script.src; newScript.type = script.type; if (script.async) newScript.async = true; if (script.defer) newScript.defer = true; document.body.appendChild(newScript); }); console.log("Document replaced with site content"); } showError(message, error) { console.error(message, error); document.body.innerHTML = `
${message}
${error.message || error}
${error.stack || JSON.stringify(error, null, 2)}