In the context of coding a chrome extension, for a certain subset of pages…
- User
In the context of coding a chrome extension, for a certain subset of pages ("https://docs.google.com/document/d/*"), if a user has a tab (with one of the targeted pages) selected (in the currently selected window), I want my extension---either via the Extension Service Worker (ESW) and/or via a Content Script (CS)---to be able to detect when the user has clicked away from that tab (to either a different chrome window, to a different tab within the same chrome window, or to window of a non-chrome program). And, I also want my extension to be able to detect if/when the user returns to that originally-selected tab (and its window).
Is there a way to accomplish these goals? If so, what is the best approach (or approaches)?
Assistant
To detect when a user leaves or returns to a specific tab (e.g., Google Docs pages), the solution must account for tab switches, window focus changes, and document visibility changes. Here's a structured approach using Chrome Extension APIs:
Key Components
- Content Script: Monitors document visibility using the
visibilitychangeevent. - Service Worker (Background):
- Tracks active tabs using
chrome.tabs.onActivated. - Tracks window focus using
chrome.windows.onFocusChanged. - Combines visibility, active tab, and window focus states to determine user presence.
- Tracks active tabs using
Implementation Steps
1. Manifest Configuration
{ "manifest_version": 3, "name": "Google Docs Activity Tracker", "version": "1.0", "permissions": [ "tabs", "windows", "https://docs.google.com/document/d/*" ], "background": { "service_worker": "service-worker.js" }, "content_scripts": [{ "matches": ["https://docs.google.com/document/d/*"], "js": ["content-script.js"] }] }
2. Content Script (
content-script.js)Monitors document visibility and sends updates to the service worker:
chrome.tabs.getCurrent(function(tab) { const tabId = tab.id; function sendVisibilityState() { chrome.runtime.sendMessage({ type: "visibility", tabId: tabId, hidden: document.hidden }); } // Initial visibility state sendVisibilityState(); // Listen for visibility changes document.addEventListener("visibilitychange", sendVisibilityState); });
3. Service Worker (
service-worker.js)Tracks tab activity, window focus, and visibility to determine user presence:
// Track active tab per window const windowActiveTab = {}; // Track focused window ID let focusedWindowId = null; // Track visibility state (document.hidden) for tabs const tabVisibility = new Map(); // Combined state for each tab: { active, focused, visible, inUse } const tabState = new Map(); // Listen for window focus changes chrome.windows.onFocusChanged.addListener((windowId) => { focusedWindowId = windowId === chrome.windows.WINDOW_ID_NONE ? null : windowId; updateTabsState(); }); // Listen for tab activation changes chrome.tabs.onActivated.addListener((activeInfo) => { windowActiveTab[activeInfo.windowId] = activeInfo.tabId; updateTabsState(); }); // Handle visibility updates from content scripts chrome.runtime.onMessage.addListener((message) => { if (message.type === "visibility") { tabVisibility.set(message.tabId, message.hidden); updateTabsState(); } }); // Update state for all target tabs function updateTabsState() { chrome.tabs.query({ url: "https://docs.google.com/document/d/*" }, (tabs) => { tabs.forEach((tab) => { const tabId = tab.id; const windowId = tab.windowId; // Current state const active = windowActiveTab[windowId] === tabId; const focused = focusedWindowId === windowId; const visible = !tabVisibility.get(tabId); // visible if not hidden // Previous state const prevState = tabState.get(tabId); const prevInUse = prevState ? prevState.inUse : false; // New state const newInUse = active && focused && visible; // Detect state changes if (newInUse !== prevInUse) { if (newInUse) { console.log(`User returned to tab ${tabId}`); // Handle return logic } else { console.log(`User left tab ${tabId}`); // Handle leave logic } } // Update state map tabState.set(tabId, { active, focused, visible, inUse: newInUse }); }); }); }
How It Works
- Tab Switch: Detected via
chrome.tabs.onActivated. If the target tab is no longer active, the user has left. - Window Focus Change: Detected via
chrome.windows.onFocusChanged. If the window loses focus (e.g., switching to another app), the user has left. - Document Visibility: Detected via
visibilitychangein the content script. If the tab is minimized or the window is inactive, the document becomes hidden.
When all three conditions (
active,focused,visible) are true, the user is considered to have returned. If any condition fails, the user is considered to have left.
Edge Cases Handled
- Minimized Windows:
visibilitychangetriggers when the window is minimized. - Non-Chrome Applications:
focusedWindowIdbecomesnullwhen switching to another app. - Multiple Chrome Windows: Tracks focus across windows.
This approach ensures comprehensive detection of user activity changes for the specified Google Docs tabs.
- Content Script: Monitors document visibility using the
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.