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
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Yes, this is definitely possible and can be accomplished primarily using the Extension Service Worker (ESW) for robust, browser-level detection, complemented by a Content Script (CS) for page-specific interactions or if you need to react to window.onfocus/onblur events (though the ESW is better for the broad "clicked away from Chrome" scenario).
The best approach combines listening to chrome.tabs and chrome.windows events in your Service Worker.
Core Concepts & APIs
Extension Service Worker (ESW):
chrome.tabs.onActivated: Fired when the active tab in a window changes. Crucial for detecting when a user switches between tabs within the same window, or when they return to your target tab. Provides activeInfo.tabId and activeInfo.windowId.
chrome.windows.onFocusChanged: Fired when the currently focused window changes. This is vital for detecting:
When a different Chrome window gains focus.
When the entire Chrome browser loses focus (e.g., user switches to VS Code, Word, etc.). In this case, windowId will be chrome.windows.WINDOW_ID_NONE.
chrome.tabs.query: To get information about currently open tabs (e.g., which one is active in a given window).
chrome.tabs.sendMessage: To communicate from the ESW to a specific Content Script.
Content Script (CS):
window.onfocus / window.onblur: These events fire when the content window itself (the iframe/tab where the page lives) gains or loses focus. This is less reliable for the overall browser/app focus but can be a secondary signal if combined with ESW data.
chrome.runtime.onMessage: To receive messages from the ESW.
Strategy
Identify and Track the Target Tab: The ESW will maintain state about which specific "https://docs.google.com/document/d/*" tab is currently being monitored (i.e., the one the user currently has selected).
Monitor Tab Activation: Use chrome.tabs.onActivated to detect when the user switches away from or back to our monitored tab.
Monitor Window Focus: Use chrome.windows.onFocusChanged to detect when the Chrome window containing our monitored tab loses or gains focus (either to another Chrome window or another application).
Communicate State to Content Script: The ESW will send messages to the relevant content script to inform it whether its tab is currently "focused" or "unfocused" based on the browser's global state.
This is the brain of your extension for this task.
javascript
3. content-script.js
This script runs within the Google Docs page. It receives messages from the ESW and can perform actions based on the focus status.
javascript
console.log("Content script loaded for Google Docs page.");
// Listen for messages from the service worker
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.type === 'TAB_FOCUS_STATUS') {
if (message.isFocused) {
console.log(`[CS] This Google Docs tab is now FOCUSED (according to ESW).`);
// Perform actions when the tab is focused:
// e.g., enable certain UI elements, start a timer, etc.
document.body.style.border = '5px solid green'; // Example visual cue
} else {
console.log(`[CS] This Google Docs tab is now UNFOCUSED (according to ESW).`);
// Perform actions when the tab is unfocused:
// e.g., pause a timer, disable UI, save state, etc.
document.body.style.border = '5px solid red'; // Example visual cue
}
}
});
// Optional: You can still listen to native window focus/blur events
// These are useful for detecting focus *within the page frame itself*
// but don't reliably tell you if the *browser window* has lost focus
// to another application or if another Chrome tab/window is focused.
window.addEventListener('focus', () => {
console.log('[CS] Window native focus event fired.');
// This fires when the content window gains focus.
// This could happen if you switch back to the tab, or if a dialog closes.
});
window.addEventListener('blur', () => {
console.log('[CS] Window native blur event fired.');
// This fires when the content window loses focus.
// This happens if you switch tabs, switch windows, or switch applications.
});
// Initial check (in case the tab is already active when the extension loads)
// The service worker will send an initial message.
How it addresses your goals:
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).
Different tab, same Chrome window:chrome.tabs.onActivated in ESW detects this.
Different Chrome window:chrome.windows.onFocusChanged in ESW detects this (windowId changes to another Chrome window ID).
Window of a non-chrome program:chrome.windows.onFocusChanged in ESW detects this (windowId becomes chrome.windows.WINDOW_ID_NONE).
In all these cases, the ESW will detect the loss of focus for the monitoredTabId and send an isFocused: false message to its content script.
Detect if/when the user returns to that originally-selected tab (and its window).
chrome.tabs.onActivated (if switching back from another tab in the same window).
chrome.windows.onFocusChanged (if switching back from another Chrome window or another application, and then the correct tab is active).
The ESW will detect the gain of focus for the monitoredTabId and send an isFocused: true message to its content script.
Considerations and Best Practices:
Active Tab Only: This solution focuses on the currently selected tab among the targeted ones. If a user has multiple docs.google.com tabs open, only the one they have active will be monitored for focus/unfocus events.
Performance: These API listeners are generally efficient and designed for this kind of monitoring. The state management in the ESW is minimal.
Communication: Always handle potential errors when sending messages to content scripts (e.g., the tab might have closed or navigated away before the message arrives). The try-catch with chrome.tabs.sendMessage is crucial.
Initial State: The updateMonitoredTabState called on onInstalled and onStartup ensures your extension correctly identifies the initially active target tab when Chrome starts or the extension is first loaded/enabled.
Tab Lifecycle: The onRemoved and onUpdated listeners help maintain the accuracy of monitoredTabId if the user closes the tab or navigates it to a non-target URL.
This comprehensive approach provides a robust and accurate way to detect the precise focus status of your targeted Google Docs tabs.
// State variables to keep track of the currently monitored tab
let monitoredTabId = null;
let monitoredWindowId = null;
// Pattern for the target URLs
const TARGET_URL_PATTERN = "https://docs.google.com/document/d/";
/**
* Checks if a given tab object matches our target URL pattern.
* @param {chrome.tabs.Tab} tab
* @returns {boolean}
*/
function isTargetTab(tab) {
return tab && tab.url && tab.url.startsWith(TARGET_URL_PATTERN);
}
/**
* Sends a focus status message to a specific tab's content script.
* @param {number} tabId
* @param {boolean} isFocused - true if the tab is focused, false otherwise.
*/
function sendFocusStatusToContentScript(tabId, isFocused) {
if (tabId) {
chrome.tabs.sendMessage(tabId, { type: 'TAB_FOCUS_STATUS', isFocused: isFocused })
.catch(error => {
// Handle error if content script isn't listening or tab is gone
if (error.message.includes("Could not establish connection. Receiving end does not exist.")) {
console.warn(`Content script not found for tab ${tabId}. It might have reloaded or closed.`);
} else {
console.error(`Error sending message to tab ${tabId}:`, error);
}
});
}
}
/**
* Updates the internal state for which tab is currently being monitored
* based on the active tab in the current window.
*/
async function updateMonitoredTabState() {
const [activeTab] = await chrome.tabs.query({ active: true, currentWindow: true });
if (isTargetTab(activeTab)) {
if (monitoredTabId !== activeTab.id || monitoredWindowId !== activeTab.windowId) {
// New target tab activated or switched to a target tab in a new window
console.log(`[ESW] Now monitoring target tab: ${activeTab.id} in window: ${activeTab.windowId}`);
// If we were monitoring a different tab, send unfocused message to it
if (monitoredTabId !== null && monitoredTabId !== activeTab.id) {
sendFocusStatusToContentScript(monitoredTabId, false);
}
monitoredTabId = activeTab.id;
monitoredWindowId = activeTab.windowId;
sendFocusStatusToContentScript(monitoredTabId, true); // This tab is now focused
}
} else {
// Current active tab is not a target tab
if (monitoredTabId !== null) {
console.log(`[ESW] Monitored tab ${monitoredTabId} is no longer active.`);
sendFocusStatusToContentScript(monitoredTabId, false); // Previously monitored tab is now unfocused
}
monitoredTabId = null;
monitoredWindowId = null;
}
}
// --- Event Listeners ---
// 1. Initial setup when extension starts or installs
chrome.runtime.onInstalled.addListener(updateMonitoredTabState);
chrome.runtime.onStartup.addListener(updateMonitoredTabState);
// 2. Listen for tab activation changes
chrome.tabs.onActivated.addListener(async (activeInfo) => {
console.log(`[ESW] Tab Activated: tabId=${activeInfo.tabId}, windowId=${activeInfo.windowId}`);
if (monitoredTabId === activeInfo.tabId && monitoredWindowId === activeInfo.windowId) {
// Our monitored tab was re-activated (e.g., switched back to it)
console.log(`[ESW] Detected return to previously monitored tab ${monitoredTabId}.`);
sendFocusStatusToContentScript(monitoredTabId, true);
} else {
// A different tab was activated. Potentially means we left the monitored tab.
// Or, the newly active tab might be a new target.
if (monitoredTabId !== null) {
// If we were monitoring a tab, it's now unfocused (because another tab is active)
console.log(`[ESW] Monitored tab ${monitoredTabId} lost focus (different tab activated).`);
sendFocusStatusToContentScript(monitoredTabId, false);
}
// Now, check if the newly activated tab is a target tab
const newlyActivatedTab = await chrome.tabs.get(activeInfo.tabId);
if (isTargetTab(newlyActivatedTab)) {
monitoredTabId = newlyActivatedTab.id;
monitoredWindowId = newlyActivatedTab.windowId;
console.log(`[ESW] New target tab ${monitoredTabId} became active.`);
sendFocusStatusToContentScript(monitoredTabId, true);
} else {
// No target tab is currently active
monitoredTabId = null;
monitoredWindowId = null;
}
}
});
// 3. Listen for window focus changes
chrome.windows.onFocusChanged.addListener(async (windowId) => {
console.log(`[ESW] Window Focus Changed: windowId=${windowId}`);
if (windowId === chrome.windows.WINDOW_ID_NONE) {
// Chrome browser lost focus (e.g., user switched to another application)
if (monitoredTabId !== null) {
console.log(`[ESW] Monitored tab ${monitoredTabId} lost focus (Chrome lost focus).`);
sendFocusStatusToContentScript(monitoredTabId, false);
}
} else if (windowId === monitoredWindowId) {
// The window containing our monitored tab regained focus
console.log(`[ESW] Monitored window ${monitoredWindowId} regained focus.`);
// Now we need to confirm if our specific tab is still the active one within it
const [activeTabInMonitoredWindow] = await chrome.tabs.query({ active: true, windowId: monitoredWindowId });
if (activeTabInMonitoredWindow && activeTabInMonitoredWindow.id === monitoredTabId) {
console.log(`[ESW] Monitored tab ${monitoredTabId} is active and focused again!`);
sendFocusStatusToContentScript(monitoredTabId, true);
} else {
// Our window regained focus, but a different tab is active, or our tab was closed/navigated.
// Re-evaluate the state of the tabs.
updateMonitoredTabState();
}
} else {
// A *different* Chrome window gained focus.
if (monitoredTabId !== null && monitoredWindowId !== null) {
console.log(`[ESW] Monitored tab ${monitoredTabId} lost focus (another Chrome window gained focus).`);
sendFocusStatusToContentScript(monitoredTabId, false);
}
// No need to update monitoredTabId here, as `onActivated` will handle if a target tab
// in the *new* focused window becomes active.
}
});
// 4. Handle tab removal (e.g., user closes the monitored tab)
chrome.tabs.onRemoved.addListener((tabId, removeInfo) => {
if (tabId === monitoredTabId) {
console.log(`[ESW] Monitored tab ${monitoredTabId} was closed.`);
monitoredTabId = null;
monitoredWindowId = null;
}
});
// 5. Handle tab navigation (e.g., user navigates away from the doc or to another doc)
chrome.tabs.onUpdated.addListener(async (tabId, changeInfo, tab) => {
// Only interested in 'complete' status as URL might not be final earlier
if (changeInfo.status === 'complete') {
if (tabId === monitoredTabId && !isTargetTab(tab)) {
// Monitored tab navigated away from a target URL
console.log(`[ESW] Monitored tab ${monitoredTabId} navigated away from target URL.`);
sendFocusStatusToContentScript(monitoredTabId, false);
monitoredTabId = null;
monitoredWindowId = null;
} else if (tab.active && tab.windowId === (await chrome.windows.getCurrent()).id && isTargetTab(tab)) {
// A target tab became active (or updated) and is the current one
// This handles cases where a user navigates from a non-doc page to a doc page in the current tab
updateMonitoredTabState();
}
}
});