detect-devtools-via-debugger-heartstop
TypeScript icon, indicating that this package has built-in type declarations

2.0.0 • Public • Published

💞🐛 Detect Devtools Via Debugger Heartstop

npm version

Detects whether the browser's devtools are open. (demo)

How It Works

  1. Main thread sends a message to a webworker thread and waits for a reply.
  2. Worker thread's message handler encounters a debugger statement.
  3. 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.
  4. 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.

Usage

See the typings file, or visit the demo page.

Alternatives

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.

Some History Readings

Readme

Keywords

Package Sidebar

Install

npm i detect-devtools-via-debugger-heartstop

Weekly Downloads

38

Version

2.0.0

License

MIT

Unpacked Size

9.21 kB

Total Files

5

Last publish

Collaborators

  • david-fong