Screenshot on Browser Focus Change: A Guide
In this article
This guide explains how to automatically capture a screenshot whenever your browser window or tab gains focus (i.e., when you switch back to it). This is useful for tracking your own activity, monitoring a web app's state, or creating visual logs for testing. You'll need a Windows, macOS, or Linux computer with a modern browser (Chrome, Edge, Firefox) and basic familiarity with the browser's developer tools or a simple script.
What You'll Need
- A computer with a browser that supports JavaScript (all modern browsers do).
- Optional: A text editor to write a small script (e.g., Notepad, VS Code).
- Optional: For automated screenshots without manual steps, you may want a browser extension like "GoFullPage" or "Awesome Screenshot" (they have auto-capture features, but we'll focus on built-in methods).
Step-by-Step
- Open the browser's Developer Console. Right-click on any page and select "Inspect" or press
F12(Windows/Linux) orCmd+Option+I(Mac). Go to the "Console" tab. - Enable the "Preserve log" option. In the Console, click the gear icon or the dropdown arrow to open console settings, then check "Preserve log." This keeps the console output when the page reloads or when you switch tabs.
- Write a focus event listener. In the console, paste the following JavaScript and press Enter:
window.addEventListener('focus', () => { console.log('Focus gained at ' + new Date().toISOString()); });This logs a message every time the window gains focus. It doesn't take a screenshot yet, but it confirms the event works. - Test the focus event. Click on another application (like your email client), then click back on the browser. You should see a new log entry with the timestamp. If you don't, ensure the console is open and the page is not in an iframe.
- Add a screenshot capture command. Replace the previous listener with this one to actually take a screenshot using the browser's built-in screenshot API (works in Chrome/Edge, not Firefox):
window.addEventListener('focus', async () => { const canvas = await html2canvas(document.body); // requires html2canvas library // Or use the built-in captureVisibleTab (only for extensions) });Note: The built-incaptureVisibleTabis only available to browser extensions. So the simplest approach is to use a keyboard shortcut manually. - Use a keyboard shortcut method. The easiest practical method: when the browser gains focus, press
PrtScn(Windows) orCmd+Shift+3(Mac) to capture the whole screen, orAlt+PrtScnfor the active window. This is manual but reliable. - Automate with a simple script (Windows). If you want true automation, create a small PowerShell script that monitors the foreground window and triggers a screenshot when it changes to your browser. Here's a basic example:
Add-Type -AssemblyName System.Windows.Forms $browserProcess = 'chrome' # change to 'firefox' or 'msedge' while ($true) { $fg = (Get-Process | Where-Object {$_.MainWindowHandle -eq (GetForegroundWindow())}).ProcessName if ($fg -eq $browserProcess) { $screenshot = [System.Windows.Forms.SystemInformation]::VirtualScreen $bitmap = New-Object System.Drawing.Bitmap $screenshot.Width, $screenshot.Height $graphics = [System.Drawing.Graphics]::FromImage($bitmap) $graphics.CopyFromScreen($screenshot.Location, [System.Drawing.Point]::Empty, $screenshot.Size) $bitmap.Save("$env:USERPROFILE\Desktop\screenshot_$(Get-Date -Format 'yyyyMMdd_HHmmss').png") Start-Sleep -Seconds 5 # avoid multiple captures } Start-Sleep -Milliseconds 500 }Run this script in PowerShell (you must have the required .NET assemblies). It will save a screenshot to your Desktop every time the browser becomes the foreground window. - For macOS, use Automator or a shell script. Create a shell script that uses
screencapturewhen the active application changes to your browser. This requires a bit of AppleScript knowledge.
Common Mistakes
- Console not preserved: If you don't enable "Preserve log," the console clears when you switch tabs, and you'll miss the focus events.
- Using
captureVisibleTabin a regular page: This API is only for extensions; it will throw an error in the console. - Focus event on the wrong element: The
focusevent onwindowfires when the window gains focus, but if you attach it to a specific element, it won't work as expected. - Script running in an iframe: If the page has iframes, the focus event might not bubble correctly. Test on a simple page first.
- PowerShell script not running: Execution policy may block scripts. Run with
Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypassin the same session.
Tips
- For quick manual captures, use
PrtScnand paste into an image editor. You can also use the Snipping Tool (Windows) orCmd+Shift+4(Mac) for a region. - If you need to capture only the browser window, use
Alt+PrtScn(Windows) orCmd+Shift+4then press Space and click the window (Mac). - To avoid overlapping screenshots, add a delay in your script (e.g., 2 seconds) after focus is detected.
- Store screenshots in a dedicated folder with timestamps to keep them organized.
- For a no-code solution, consider a browser extension like "Auto Screenshot" that can capture on tab switch (but be cautious with permissions).
Troubleshooting
- No focus event logged: Make sure you pasted the code correctly and pressed Enter. Also, check that the console is open and the page is not in a cross-origin iframe.
- PowerShell script not saving screenshots: Verify that the browser process name matches (e.g.,
chrome,firefox,msedge). UseGet-Processto see the exact name. - Script captures the wrong window: The
GetForegroundWindowAPI may return the console window if you run the script from the console. Run the script in the background or use a scheduled task. - Permissions denied for saving files: Ensure the target folder exists and you have write permissions. Try saving to a temp folder first.
- Browser extension conflicts: If you use an extension that captures screenshots, it might interfere. Disable other screenshot extensions temporarily.
Frequently Asked Questions
Can I take a screenshot automatically without any script?
Yes, some browser extensions like "Auto Capture" or "Screen Recorder" can be set to capture on tab switch, but they often require manual configuration and may have limitations.
Does this work on all browsers?
The JavaScript focus event works in all modern browsers. The screenshot automation script is OS-specific; the provided PowerShell example works on Windows, and similar scripts can be made for macOS using AppleScript.
Can I capture only the browser window, not the whole screen?
Yes, on Windows use Alt+PrtScn manually. In a script, you can use the MainWindowHandle to capture only that window, but it requires more complex code.
Will this work if I have multiple monitors?
The PowerShell script captures the virtual screen (all monitors). To capture only the primary monitor, adjust the screen bounds to PrimaryScreen.Bounds.
Is there a way to capture only when a specific tab is active?
Yes, you can check document.hasFocus() inside the focus event to see if the specific tab is active. If not, you can ignore the event.
Can I use this for security monitoring?
This is for your own device and activity. Using it to monitor others without consent may violate privacy laws. Always get permission.