// Content script on Teams web: logs active speaker, shares, captions, chat, hands, presence while recording. // Events go via the offscreen document (it has host_permissions for 127.0.0.1). Never clicks or types in the call. // DOM selectors for the Teams web client. The data-tid attributes are Teams' internal test ids and can change with Teams releases. const SEL = { // Call elapsed-time element. duration: '[data-tid="call-duration"]', // Name label inside each participant tile. nametag: '[data-tid="participant-info-nametag"]', // Participant info container. info: '[data-tid="participant-info"]', // Speaking outline: data-is-speaking="true" while the participant talks. speaking: '[data-tid="voice-level-stream-outline"][data-is-speaking="true"]', // The local user's own video tile. self: '[data-tid="myself-video"]', // Screen-share banner aria-label (English and Italian UI); group 2 is the sharer's name. shareAria: /^(Contenuto condiviso da|Content shared by) (.+)$/, caption: '[data-tid="author"],[data-tid="closed-caption-text"]', // DOM order; author only on first row of a speaker's run // Chat selectors not found yet (null): chat capture is disabled. chatMsg: null, chatAuthor: null, chatText: null, // discovery step // Raised-hand selector not found yet (null): hand capture is disabled. hand: null, // discovery step }; // State: buf = queued events; timers = intervals; seenCap = caption rows already emitted; capAuthor = last caption speaker; seenChat; lastShare = current sharer; raised = hands up; lastTitle = last title sent. let buf = [], timers = [], seenCap = new WeakMap(), capAuthor = "", seenChat = new WeakSet(), lastShare = "", raised = new Set(), lastTitle = null; // Normalise a Teams display name: "LAST, First (Org)" -> "First Last"; ALL-CAPS words are title-cased. const norm = raw => { raw = (raw || "").trim(); // Matches "Last, First" with an optional "(...)" suffix; anything else is returned trimmed. const match = raw.match(/^([^,]+),\s*([^(]+?)\s*(\(.*)?$/); if (!match) return raw; // Reorder to "First Last" and title-case words that are fully uppercase. return `${match[2]} ${match[1]}`.split(/\s+/).map(word => (word.length > 1 && word === word.toUpperCase() ? word[0] + word.slice(1).toLowerCase() : word)).join(" "); }; // Walk up from an element to the participant tile (the ancestor containing a name tag). const tileOf = element => { while (element && !element.querySelector(SEL.nametag)) element = element.parentElement; return element; }; // Stable participant key: the nearest ancestor data-tid containing "@" (an id), else the name text. const keyOf = tile => { for (let node = tile; node; node = node.parentElement) if ((node.dataset?.tid || "").includes("@")) return node.dataset.tid; return tile.querySelector(SEL.nametag)?.textContent.trim() || ""; }; // Display name from a tile's name tag. const nameOf = tile => norm(tile.querySelector(SEL.nametag)?.textContent); // Name of the local user, read from the self-video tile. const selfName = () => { const selfTile = document.querySelector(SEL.self); return selfTile ? nameOf(selfTile) : ""; }; // Queue an event with a wall-clock timestamp; sent later by send(). const emit = (kind, who_key = "", who = "", text = "") => buf.push({ ts: Date.now(), kind, who_key, who, text }); // Wrap timer callbacks so one exception does not kill the interval. const guard = callback => () => { try { callback(); } catch (error) { console.error("[teams-whisper]", error); } }; // Send queued events to the offscreen document; errors ignored (the recorder may be closed). const send = () => { if (buf.length) chrome.runtime.sendMessage({ to: "off", cmd: "events", events: buf.splice(0) }).catch(() => { }); }; // All participant tiles currently in the DOM. const tiles = () => [...document.querySelectorAll(SEL.nametag)].map(tileOf).filter(Boolean); // Emit the meeting title and call elapsed time, but only when the title changes. function meta() { // Page title looks like "Meeting | Name | Microsoft Teams": drop the leading segment and the trailing suffix. const title = document.title.replace(/^[^|]*\|\s*/, "").replace(/\s*\|\s*Microsoft Teams$/, ""); // Nothing new since last time. if (title === lastTitle) return; lastTitle = title; // Payload is JSON in the text field. emit("meta", "", "", JSON.stringify({ title, call_elapsed: document.querySelector(SEL.duration)?.textContent.trim() || "", url: location.href })); } // Roster snapshot: one entry per participant key. function present() { // Dedupe by key (a participant can have more than one tile). const seen = new Map(); // The self tile's name comes from the self-video element. for (const tile of tiles()) seen.set(keyOf(tile), { key: keyOf(tile), who: tile.closest(SEL.self) ? selfName() : nameOf(tile) }); // Roster snapshot payload. emit("present", "", "", JSON.stringify([...seen.values()])); } // Emit one "active" event for each participant whose speaking outline is on. function active() { // Speaking outlines in the DOM. for (const element of document.querySelectorAll(SEL.speaking)) { const tile = tileOf(element); if (!tile) continue; // The local user speaking is recorded under the key "self". if (tile.closest(SEL.self) || tile.matches(SEL.self)) emit("active", "self", selfName()); else emit("active", keyOf(tile), nameOf(tile)); } } // Screen share: detect the sharer from the banner aria-label and emit start/stop on change. function share() { // Roster names to match the banner text against. const names = tiles().map(nameOf); let cur = ""; // Scan all aria-labels for the share banner. for (const element of document.querySelectorAll("[aria-label]")) { const match = element.getAttribute("aria-label").match(SEL.shareAria); // Prefer a roster name the banner text starts with (labels can be truncated); else use the raw text. if (match) { cur = names.find(name => name && match[2].startsWith(name)) || match[2]; break; } } // No change since last check. if (cur === lastShare) return; // Previous sharer stopped. if (lastShare) emit("share_stop", "", lastShare); if (cur) emit("share_start", "", cur); lastShare = cur; } // Captions, chat and raised hands, each emitted once. function messages() { if (SEL.caption) for (const element of document.querySelectorAll(SEL.caption)) { // Author row sets the speaker for the text rows that follow it. if (element.getAttribute("data-tid") === "author") { capAuthor = norm(element.textContent); continue; } // caption text grows while spoken: emit once it was unchanged for a full tick // Caption text of this row. const text = element.textContent.trim(), seenState = seenCap.get(element) || {}; // Already emitted this row. if (seenState.done) continue; // Unchanged since last tick: treat as final and emit once. if (text && seenState.text === text) { seenState.done = true; emit("caption", "", capAuthor, text); } seenState.text = text; seenCap.set(element, seenState); } // Chat messages (inactive while SEL.chatMsg is null); each element is counted once. if (SEL.chatMsg) for (const element of document.querySelectorAll(SEL.chatMsg)) { if (seenChat.has(element)) continue; seenChat.add(element); const text = element.querySelector(SEL.chatText)?.textContent.trim(); if (text) emit("chat", "", norm(element.querySelector(SEL.chatAuthor)?.textContent), text); } // Hand raises (inactive while SEL.hand is null); emit only new raises. if (SEL.hand) { // Hands raised this tick. const now = new Set(); for (const element of document.querySelectorAll(SEL.hand)) { const tile = tileOf(element); if (!tile) continue; const participantKey = keyOf(tile); now.add(participantKey); // New raise since the last tick. if (!raised.has(participantKey)) emit("hand", participantKey, nameOf(tile)); } // Keep only hands still up. raised = now; } } // Stop: clear timers, flush pending events, and close any open share. function stop() { timers.forEach(clearInterval); timers = []; send(); if (lastShare) { emit("share_stop", "", lastShare); lastShare = ""; } send(); } // Start a fresh recording: stop old timers, then reset per-recording state. function start() { stop(); // Reset per-recording state. buf = []; seenCap = new WeakMap(); capAuthor = ""; seenChat = new WeakSet(); raised = new Set(); lastTitle = null; lastShare = ""; // Emit the initial snapshot right away. meta(); present(); // Periodic scans: speaker 500 ms, share and captions 1 s, roster 30 s, flush 5 s. timers = [ setInterval(guard(() => { meta(); active(); }), 500), setInterval(guard(share), 1000), setInterval(guard(messages), 1000), setInterval(guard(present), 30000), setInterval(guard(send), 5000), ]; } // Start/stop commands sent by popup.js directly to this tab. chrome.runtime.onMessage.addListener(message => { if (message.cmd === "cap-start") start(); if (message.cmd === "cap-stop") stop(); });