💞 🐛 Detect Devtools Via Debugger Heartstop
Detects whether the browser's devtools are open. (demo)
How It Works
- Main thread sends a message to a webworker thread and waits for a reply.
- Worker thread's message handler encounters a debugger statement.
- If devtools are closed, the worker will immediately send an acknowledgement to the main thread, and the main thread will do a sanity check that the timestamp of the acknowledgement is recent enough that devtools were probably closed.
- If devtools are opened, the worker will enter a debugging session, and the main thread will timeout waiting for the response, concluding that the debugger must be open. The main thread will not be blocked by the worker's debugging session, but it's timeout response will be blocked by any heavy processing in the main thread ahead of it in the event queue.
This was a fun challenge to tackle. If this solution sounds overly complex, take a look through the listed alternatives. It's a pretty fascinating rabbit hole.
Pros and Cons
To devs who want some custom browser hooks for their own purposes, this is not for you. You will hate it. It will enter debugging for the worker thread whenever devtools are opened, which (in most browsers) also causes the console context to change to the worker's context. Simply continuing the debugger will result in the debugger activating again, and the only way around this is to use the browser's inbuilt mechanism to disable all breakpoints (which may need to be done each time opening the devtools depending on whether your browser remembers the setting). Scroll down for links to alternatives.
This is well suited for devs who want to do silly/weird things to users such as rickrolling people who open devtools in a browser game, and don't mind absolutely destroying the usability/ergonomics of the devtools.
This has the benefit over other implementations that it doesn't depend on whether the devtools pane is attached to the browser window, or other deeply browser-internal behaviours such as lazy console logging of complex objects, which are much more subject to change.
Though the design involves timing program execution, it is written such that the detection should never trigger false positives due to busy threads, given a reasonable main thread timeout value.
- https://github.com/dsa28s/detect-browser-devtools - uses somewhat specific browser behaviours
- https://github.com/sindresorhus/devtools-detect - compares the page dimensions to the window dimensions
You may also have luck sifting through the below StackOverflow thread. For example, one simple but non-robust way to do it is to hook into keyboard shortcuts.