← 教程列表
news

Task 2: Create the Helper Library

📅 2026/6/12 16:30:02⏱ 约 5 分钟阅读👁 8 阅读

**Files:** - Create: `lib/brainstorm-server/helper.js` **Step 1: Create helper.js with event auto-capture** ```javascript (function() { const WS_URL = 'ws://' + window.location.host; let ws = null; let eventQueue = []; function connect() { ws = new WebSocket(WS_URL); ws.onopen = () => { // Send any queued events eventQueue.forEach(e => ws.send(JSON.stringify(e))); eventQueue = []; }; ws.onmessage = (msg) => { const data = JSON.parse(msg.data); if (data.type === 'reload') { window.location.reload(); } }; ws.onclose = () => { // Reconnect after 1 second setTimeout(connect, 1000); }; } function send(event) { event.timestamp = Date.now(); if (ws && ws.readyState === WebSocket.OPEN) { ws.send(JSON.stringify(event)); } else { eventQueue.push(event); } } // Auto-capture clicks on interactive elements document.addEventListener('click', (e) => { const target = e.target.closest('button, a, [data-choice], [role="button"], input[type="submit"]'); if (!target) return; // Don't capture regular link navigation if (target.tagName === 'A' && !target.dataset.choice) return; e.preventDefault(); send({ type: 'click', text: target.textContent.trim(), choice: target.dataset.choice || null, id: target.id || null, className: target.className || null }); }); // Auto-capture form submissions document.addEventListener('submit', (e) => { e.preventDefault(); const form = e.target; const formData = new FormData(form); const data = {}; formData.forEach((value, key) => { data[key] = value; }); send({ type: 'submit', formId: form.id || null, formName: form.name || null, data: data }); }); // Auto-capture input changes (debounced) let inputTimeout = null; document.addEventListener('input', (e) => { const target = e.target; if (!target.matches('input, textarea, select')) return; clearTimeout(inputTimeout); inputTimeout = setTimeout(() => { send({ type: 'input', name: target.name || null, id: target.id || null, value: target.value, inputType: target.type || target.tagName.toLowerCase() }); }, 500); // 500ms debounce }); // Expose for explicit use if needed window.brainstorm = { send: send, choice: (value, metadata = {}) => send({ type: 'choice', value, ...metadata }) }; connect(); })(); ``` **Step 2: Verify helper.js is syntactically valid** Run: `node -c lib/brainstorm-server/helper.js` Expected: No syntax errors **Step 3: Commit** ```bash git add lib/brainstorm-server/helper.js git commit -m "feat: add browser helper library for event capture" ``` ---

← 返回教程列表 AI8899 · 内容仅供学习参考