Skip to content

Instantly share code, notes, and snippets.

@manix84
Last active July 2, 2025 11:27
Show Gist options
  • Select an option

  • Save manix84/992374a8e186d393dc6c1ade316b1fd0 to your computer and use it in GitHub Desktop.

Select an option

Save manix84/992374a8e186d393dc6c1ade316b1fd0 to your computer and use it in GitHub Desktop.
Detect if the user has opened the browser console.
/**
This code is licensed under the terms of the MIT license
*/
import { useEffect, useRef, useState } from 'react';
type UseConsoleOpenOptions = {
onOpen?: () => void;
pollInterval?: number;
};
export function useConsoleOpen({ onOpen, pollInterval = 1000 }: UseConsoleOpenOptions = {}): boolean {
const [isConsoleOpen, setIsConsoleOpen] = useState(false);
const hasFired = useRef(false);
useEffect(() => {
const detectConsole = () => {
let open = false;
const element = new Image();
Object.defineProperty(element, 'id', {
get() {
open = true;
return '';
},
});
console.log('%c', element);
if (open && !hasFired.current) {
hasFired.current = true;
setIsConsoleOpen(true);
onOpen?.();
} else if (!open && isConsoleOpen) {
setIsConsoleOpen(false);
hasFired.current = false; // allow re-trigger if console is closed and reopened
}
};
detectConsole(); // initial check
const intervalId = setInterval(detectConsole, pollInterval);
return () => clearInterval(intervalId);
}, [pollInterval, onOpen, isConsoleOpen]);
return isConsoleOpen;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment