Okay, this is a common scenario for extensions needing to react to user focus shifts. The best approach involves a combination of the Extension Service Worker (ESW) for global state and Chrome API event listening, and Content Scripts (CS) for interacting directly with the page's focus events.
Here's a breakdown of the approach:
Core Idea:
- ESW: Monitors Chrome-level events (
tabs.onActivated, windows.onFocusChanged). It keeps track of the specific Google Doc tab that currently has focus. When focus shifts away from this tracked tab, the ESW tells the corresponding Content Script to start listening for page-level focus events (blur). When focus returns to the tracked tab, the ESW tells the Content Script to stop listening (or just stops sending messages).
- CS: Injected into the targeted Google Docs pages. It primarily listens for the browser window's
blur and focus events. When the ESW tells it to start listening (because the tab became active), it attaches these listeners. The blur event fires when the user navigates away (to another tab, another window, or another application). The focus event fires when they return to that specific tab. The CS then reports these events back to the ESW.
Implementation Details:
1. manifest.json
{
"manifest_version": 3,
"name": "Tab Focus Tracker",
"version": "1.0",
"permissions": [
"tabs", // To query and send messages to tabs
"scripting" // Needed for chrome.tabs.sendMessage in MV3 if not using declarative injection exclusively for listeners
// "activeTab" might be useful but less direct than tracking specific URLs
],
"background": {
"service_worker": "background.js"
},
"content_scripts": [
{
"matches": ["https://docs.google.com/document/d/*"],
"js": ["content.js"],
"run_at": "document_start" // Inject early to potentially catch focus events
}
]
}
2. background.js (Extension Service Worker)
// --- State Variables ---
let activeTargetedTabId = null;
let activeTargetedWindowId = null;
let trackedTabInfo = null; // Store {tabId, windowId, url}
// --- Helper Function ---
function isTargetUrl(url) {
if (!url) return false;
// Basic check, could be more robust if needed
return url.startsWith("https://docs.google.com/document/d/");
}
// --- Listen for Tab Activation ---
chrome.tabs.onActivated.addListener(async (activeInfo) => {
console.log("Tab Activated:", activeInfo);
const tab = await chrome.tabs.get(activeInfo.tabId);
// Reset state if the previously tracked tab lost focus implicitly
if (activeTargetedTabId && activeTargetedTabId !== tab.id) {
console.log(`Tab ${activeTargetedTabId} implicitly lost focus.`);
sendMessageToTab(activeTargetedTabId, { type: "stopListening" });
activeTargetedTabId = null;
activeTargetedWindowId = null;
trackedTabInfo = null;
}
// If the newly activated tab is a target
if (tab && isTargetUrl(tab.url) && tab.active) {
console.log(`New active tab is a target: ${tab.id}`);
// If it's different from the previously tracked one, stop the old one
if (activeTargetedTabId && activeTargetedTabId !== tab.id) {
console.log(`Stopping tracking for previous tab ${activeTargetedTabId}`);
sendMessageToTab(activeTargetedTabId, { type: "stopListening" });
}
// Start tracking the new one
activeTargetedTabId = tab.id;
activeTargetedWindowId = tab.windowId;
trackedTabInfo = { tabId: tab.id, windowId: tab.windowId, url: tab.url };
console.log(`Starting tracking for tab ${tab.id} in window ${tab.windowId}`);
// Tell the content script in this new tab to start listening
sendMessageToTab(tab.id, { type: "startListening" });
} else {
// Activated tab is NOT a target, ensure we stop tracking if we were
if (activeTargetedTabId) {
console.log(`Activated tab ${tab.id} is not a target. Stopping tracking for ${activeTargetedTabId}.`);
sendMessageToTab(activeTargetedTabId, { type: "stopListening" });
activeTargetedTabId = null;
activeTargetedWindowId = null;
trackedTabInfo = null;
}
}
});
// --- Listen for Window Focus Changes ---
chrome.windows.onFocusChanged.addListener(async (windowId) => {
console.log("Window Focus Changed:", windowId);
// Case 1: Focus moved away from *any* Chrome window (or Chrome is minimized/closed)
if (windowId === chrome.windows.WINDOW_ID_NONE) {
if (activeTargetedTabId) {
console.log(`Focus lost completely (windowId NONE). Stopping tracking for ${activeTargetedTabId}.`);
sendMessageToTab(activeTargetedTabId, { type: "stopListening" });
activeTargetedTabId = null;
activeTargetedWindowId = null;
trackedTabInfo = null;
}
return;
}
// Case 2: Focus moved to a *different* Chrome window
if (activeTargetedWindowId && windowId !== activeTargetedWindowId) {
console.log(`Focus moved to different window ${windowId}. Stopping tracking for ${activeTargetedTabId}.`);
sendMessageToTab(activeTargetedTabId, { type: "stopListening" });
activeTargetedTabId = null;
activeTargetedWindowId = null;
trackedTabInfo = null;
}
// Case 3: Focus moved to a Chrome window that *might* contain our target tab
// Check if the newly focused window has an active targeted tab
try {
const activeTabs = await chrome.tabs.query({ active: true, windowId: windowId });
if (activeTabs.length > 0) {
const currentTab = activeTabs[0];
console.log("Checking focused window's active tab:", currentTab.id, currentTab.url);
if (isTargetUrl(currentTab.url)) {
// If we weren't tracking anything, or if the focus shifted *within* the target window
// but to a different tab that is also a target (less likely but possible)
if (!activeTargetedTabId || activeTargetedTabId !== currentTab.id) {
console.log(`New window focus contains target tab ${currentTab.id}.`);
// Stop previous if necessary
if(activeTargetedTabId && activeTargetedTabId !== currentTab.id) {
sendMessageToTab(activeTargetedTabId, { type: "stopListening" });
}
// Start tracking the new one
activeTargetedTabId = currentTab.id;
activeTargetedWindowId = windowId;
trackedTabInfo = { tabId: currentTab.id, windowId: windowId, url: currentTab.url };
console.log(`Starting tracking for tab ${currentTab.id} in window ${windowId}`);
sendMessageToTab(currentTab.id, { type: "startListening" });
}
} else {
// Focused window's active tab is NOT a target, stop tracking if we were
if (activeTargetedTabId) {
console.log(`Focused window's active tab ${currentTab.id} is not target. Stopping tracking for ${activeTargetedTabId}.`);
sendMessageToTab(activeTargetedTabId, { type: "stopListening" });
activeTargetedTabId = null;
activeTargetedWindowId = null;
trackedTabInfo = null;
}
}
}
} catch (error) {
console.error("Error querying tabs after focus change:", error);
// Might happen if the window was closed quickly. Reset state.
if (activeTargetedTabId) {
sendMessageToTab(activeTargetedTabId, { type: "stopListening" });
activeTargetedTabId = null;
activeTargetedWindowId = null;
trackedTabInfo = null;
}
}
});
// --- Listen for Messages from Content Scripts ---
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
// Ensure the message is from the correct content script context
if (!sender.tab || !isTargetUrl(sender.tab.url)) {
// Optionally handle messages from non-target scripts if needed
return;
}
const senderTabId = sender.tab.id;
// Message from CS saying it's ready and listening for focus/blur
if (message.type === "readyAndListening") {
console.log(`Content script ready in tab ${senderTabId}`);
// This confirms the CS is active. If this tab IS the tracked tab, we're good.
// If it's NOT the tracked tab, it means the user switched away before ESW could tell it to stop.
// We should ensure the ESW tells it to stop if it's not the active one.
if (activeTargetedTabId && senderTabId !== activeTargetedTabId) {
console.log(`Tab ${senderTabId} reported ready, but isn't the active target. Telling it to stop.`);
sendMessageToTab(senderTabId, { type: "stopListening" });
}
sendResponse({ ack: "Received ready state" }); // Optional ack
}
// Message from CS when the page's window lost focus
else if (message.type === "pageWindowBlurred") {
console.log(`Received pageWindowBlurred from tab ${senderTabId}`);
// Only act if this is the tab we are currently tracking
if (senderTabId === activeTargetedTabId) {
console.log(`Tracked tab ${senderTabId} lost page focus.`);
// Tell the CS to stop listening now that focus is lost
sendMessageToTab(senderTabId, { type: "stopListening" });
// Mark that we are no longer tracking this tab as active
activeTargetedTabId = null;
activeTargetedWindowId = null;
trackedTabInfo = null;
// Note: We don't know *where* the user went, just that they left this tab.
}
}
// Message from CS when the page's window gained focus
else if (message.type === "pageWindowFocused") {
console.log(`Received pageWindowFocused from tab ${senderTabId}`);
// Only act if this is the tab we are currently tracking and expecting focus back
if (senderTabId === activeTargetedTabId) {
console.log(`Tracked tab ${senderTabId} regained page focus.`);
// The ESW should already know this tab is active via onActivated/onFocusChanged.
// We might want to re-confirm listeners are active or simply rely on the ESW's state.
// If the ESW thinks focus is lost (e.g., manual reset), it might restart listening here.
// For simplicity, let's assume ESW manages the start/stop state based on Chrome events.
// If ESW logic is correct, this message just confirms focus *within* the tab.
// A potential use: If ESW lost track somehow, this message could re-initiate tracking.
if (!trackedTabInfo || trackedTabInfo.tabId !== senderTabId) {
console.warn(`Focus returned to ${senderTabId}, but ESW state was lost. Re-establishing.`);
// Re-query tab info might be needed if state is critical
chrome.tabs.get(senderTabId).then(tab => {
activeTargetedTabId = tab.id;
activeTargetedWindowId = tab.windowId;
trackedTabInfo = { tabId: tab.id, windowId: tab.windowId, url: tab.url };
sendMessageToTab(senderTabId, { type: "startListening" }); // Ensure listening
});
}
}
}
// Important: Return true to indicate you might send a response asynchronously
// (though not strictly needed in this example if responses aren't critical)
return true;
});
// Helper to send messages, handling potential errors (e.g., tab closed)
async function sendMessageToTab(tabId, message) {
try {
await chrome.tabs.sendMessage(tabId, message);
console.log(`Message sent to tab ${tabId}:`, message.type);
} catch (error) {
console.warn(`Could not send message to tab ${tabId}:`, error.message);
// If the error is "Could not send message to background page", it might mean the tab is closing or gone.
// Clean up state related to this tab if it was the active one.
if (activeTargetedTabId === tabId) {
console.log(`Tab ${tabId} seems gone. Clearing tracked state.`);
activeTargetedTabId = null;
activeTargetedWindowId = null;
trackedTabInfo = null;
}
}
}
// --- Initial Setup ---
// Optional: Find the currently active tab when the extension starts
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
if (tabs.length > 0 && isTargetUrl(tabs[0].url)) {
console.log("Extension started with target tab active:", tabs[0].id);
activeTargetedTabId = tabs[0].id;
activeTargetedWindowId = tabs[0].windowId;
trackedTabInfo = { tabId: tabs[0].id, windowId: tabs[0].windowId, url: tabs[0].url };
// No need to send startListening here, the CS will send 'readyAndListening'
// when it loads, and the ESW will handle it. We just need the initial state set.
}
});
3. content.js (Content Script)
// --- State ---
let isListening = false; // Track if this script is actively listening
// --- Functions ---
function handleFocus() {
console.log("Content Script: Window focus detected!");
if (isListening) {
// Send message to background script that focus was regained
chrome.runtime.sendMessage({ type: "pageWindowFocused" });
}
}
function handleBlur() {
console.log("Content Script: Window blur detected!");
if (isListening) {
// Send message to background script that focus was lost
chrome.runtime.sendMessage({ type: "pageWindowBlurred" });
// Important: Stop listening immediately after blur is detected
// to avoid redundant messages and potential loops if focus flickers.
stopListeningForFocus();
}
}
function startListeningForFocus() {
if (!isListening) {
console.log("Content Script: Starting to listen for focus/blur events.");
window.addEventListener("focus", handleFocus);
window.addEventListener("blur", handleBlur);
isListening = true;
// Inform the background script that we are now actively listening
chrome.runtime.sendMessage({ type: "readyAndListening" });
}
}
function stopListeningForFocus() {
if (isListening) {
console.log("Content Script: Stopping listening for focus/blur events.");
window.removeEventListener("focus", handleFocus);
window.removeEventListener("blur", handleBlur);
isListening = false;
}
}
// --- Listen for Commands from Background Script ---
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
console.log("Content Script received message:", message.type);
if (message.type === "startListening") {
startListeningForFocus();
} else if (message.type === "stopListening") {
stopListeningForFocus();
}
// No need to return true unless sending async response
});
// --- Initial Check ---
// When the content script loads, it should immediately tell the background script
// it's ready IF it's in the currently active tab. The background script will
// then decide if it needs to start listening.
// This helps handle cases where the extension loads after the tab is already active.
if (document.hasFocus()) { // Check if the tab *initially* has focus when CS loads
console.log("Content Script loaded in focused tab. Informing background.");
// Send a message indicating readiness. The ESW will check if this tab needs tracking.
chrome.runtime.sendMessage({ type: "readyAndListening" });
} else {
// If the tab does NOT have focus when CS loads, it doesn't need to report readiness
// immediately, but it *should* start listening if the ESW later tells it to.
console.log("Content Script loaded in blurred tab. Waiting for instructions.");
// We might want to send a 'ping' or similar, but the ESW's `onFocusChanged` should handle switching back.
}
// Note: We don't need to add listeners immediately on load. The ESW coordinates *when*
// the CS should actively listen using start/stop messages.
Explanation:
- Initialization: The ESW starts by checking if the currently active tab is one of the target URLs.
- Tab Activation: When
chrome.tabs.onActivated fires, the ESW checks the new tab's URL.
- If it's a target tab, it tells the previously tracked tab's CS (if any) to
stopListening and tells the new tab's CS to startListening. It updates its internal state (activeTargetedTabId, etc.).
- If it's not a target tab, it tells the previously tracked CS (if any) to
stopListening and clears its internal state.
- Window Focus Change:
chrome.windows.onFocusChanged helps catch focus shifts between Chrome windows or away from Chrome entirely (WINDOW_ID_NONE). The ESW uses this to update its state and tell the relevant CS to stop listening. It also checks if focus moved to a window containing a target tab and initiates tracking if necessary.
- Content Script (
content.js):
- It listens for
startListening and stopListening messages from the ESW.
- When
startListening is received, it adds listeners for the page's native window.onfocus and window.onblur events. It also sends a readyAndListening message back to the ESW for confirmation.
- When
stopListening is received, it removes these listeners.
handleBlur: This is the key event. When the user clicks away (anywhere – another tab, app, etc.), the Google Doc's window blurs. The CS catches this, sends pageWindowBlurred to the ESW, and importantly, immediately stops listening itself. This prevents multiple "blur" events from being sent if focus flickers.
handleFocus: When the user clicks back specifically onto the Google Doc tab, the window focus event fires. The CS catches this and sends pageWindowFocused to the ESW.
- Detecting Outside Chrome: The
window.onblur event triggered in the Content Script is the most reliable way to detect this. When you switch to another application, the browser window (and thus the tab's document) loses focus, firing blur.
This hybrid approach ensures that listeners are only active when necessary (on the targeted, active tab) and uses the most appropriate events at each level (Chrome API events for window/tab switching, DOM events for page-level focus changes).