DEV Community

Ion Prodan
Ion Prodan

Posted on • Originally published at yon.fun on

Detect chrome dev tools (working trick)

Detect chrome dev tools (working trick)

Have you ever thought about how to detect if the chrome dev tools is opened or not, even more, listen when it's opening? I have, and today I'm going to show a simple trick.

After some Google researches, I found many tricks but unfortunately, many of them aren't working anymore. There's just one solution (after me) which can deal with that. Take a look to this (copy and paste it to your code, it's ready to use solution):

const element = new Image();
Object.defineProperty(element, 'id', {
  get: function () {
    /* Call callback function here */
  }
});
console.log('%c', element);
Enter fullscreen mode Exit fullscreen mode
Detect Chrome Dev Tools Javascript Code

Let's dive into it a bit and understand what's going on there. So, first of all, we create an element (it doesn't require to be new Image(), I think new Audio() would work just as well), we use Object.defineProperty to define the id property of the element and add a function callback on get. Pretty clever, right? Now every time when the element.id is taken, the callback function will run - that's what we need, put there the functions to run when chrome dev tools will be opened.

So the interesting part is the last line, why callback function is not running if the console.log is already called which means element.id as well? Well, it's not true, console.log is called only when chrome dev console tool is opened which tries to log element as well as id property - and what's happening when id property is taken? Right, it triggers the (get) callback function.

Do you know other tricks that nowadays really work? Share them with us, I'll include in this article.

Top comments (0)