Find out whether Chrome console is open

2019-01-01 06:42发布

问题:

I am using this little script to find out whether Firebug is open:

if (window.console && window.console.firebug) {
    //is open
};

And it works well. Now I was searching for half an hour to find a way to detect whether Google Chrome\'s built-in web developer console is open, but I couldn\'t find any hint.

This:

if (window.console && window.console.chrome) {
    //is open
};

doesn\'t work.

EDIT:

So it seems that it is not possible to detect whether the Chrome console is open. But there is a \"hack\" that works, with some drawbacks:

  • will not work when console is undocked
  • will not work when console is open on page load

So, I am gonna choose Unsigned´s answer for now, but if some1 comes up with a brilliant idea, he is welcome to still answer and I change the selected answer! Thanks!

回答1:

toString (2017-2018)

Since the original asker doesn\'t seem to be around anymore and this is still the accepted answer, adding this solution for visibility. Credit goes to Antonin Hildebrand\'s comment on zswang\'s answer. This solution takes advantage of the fact that toString() is not called on logged objects unless the console is open.

var devtools = /./;
devtools.toString = function() {
  this.opened = true;
}

console.log(\'%c\', devtools);
// devtools.opened will become true if/when the console is opened

console.profiles (2013)

Update: console.profiles has been removed from Chrome. This solution no longer works.

Thanks to Paul Irish for pointing out this solution from Discover DevTools, using the profiler:

function isInspectOpen()
{
    console.profile(); 
    console.profileEnd(); 
    if (console.clear) console.clear();
    return console.profiles.length > 0;
}

window.innerHeight (2011)

This other option can detect the docked inspector being opened, after the page loads, but will not be able to detect an undocked inspector, or if the inspector was already open on page load. There is also some potential for false positives.

window.onresize = function()
{
    if ((window.outerHeight - window.innerHeight) > 100)
        alert(\'Docked inspector was opened\');
}


回答2:

Chrome 65+ (2018)

r = /./
r.toString = function () {
    document.title = \'1\'
}
console.log(\'%c\', r);

demo: https://jsbin.com/cecuzeb/edit?output (Update at 2018-03-16)

package: https://github.com/zswang/jdetects


When printing “Element” Chrome developer tools will get its id

var checkStatus;

var element = document.createElement(\'any\');
element.__defineGetter__(\'id\', function() {
    checkStatus = \'on\';
});

setInterval(function() {
    checkStatus = \'off\';
    console.log(element);
    console.clear();
}, 1000);

Another version (from comments)

var element = new Image();
Object.defineProperty(element, \'id\', {
  get: function () {
    /* TODO */
    alert(\'囧\');
  }
});
console.log(\'%cHello\', element);

Print a regular variable:

var r = /./;
r.toString = function() {
  document.title = \'on\';
};
console.log(r);


回答3:

I created devtools-detect which detects when DevTools is open:

console.log(\'is DevTools open?\', window.devtools.open);

You can also listen to an event:

window.addEventListener(\'devtoolschange\', function (e) {
    console.log(\'is DevTools open?\', e.detail.open);
});

It doesn\'t work when DevTools is undocked. However, works with the Chrome/Safari/Firefox DevTools and Firebug.



回答4:

I found a way to tell if the Chrome Console is opened or not. It’s still a hack but it’s way more accurate and will work weather the console is undocked or not.

Basically running this code with the console closed takes about ~100 microseconds and while the console is opened it takes about twice as much ~200 microseconds.

console.log(1);
console.clear();

(1 millisecond = 1000 microsecond)

I’ve written more about it here.

Demo is here.


Update:

@zswang has found the current best solution - check out his answer



回答5:

If your goal is to jam the developer tools, try this (I found a more complicated version of it at a place where JS code was obfuscated, it\'s very annoying):

setTimeout(function() {while (true) {eval(\"debugger\");}}, 0);


回答6:

I found a new method:

var b=new Blob()
Object.defineProperty(b,\'size\',{get(){
    alert(\'The devtool was opened!\')
}})
setTimeout(function(){console.log(b)},3000)

test online



回答7:

There is a tricky way to check it for extensions with \'tabs\' permission:

chrome.tabs.query({url:\'chrome-devtools://*/*\'}, function(tabs){
    if (tabs.length > 0){
        //devtools is open
    }
});

Also you can check if it open for your page:

chrome.tabs.query({
    url: \'chrome-devtools://*/*\',
    title: \'*example.com/your/page*\'
}, function(tabs){ ... })


回答8:

I wrote a blog post about this: http://nepjua.org/check-if-browser-console-is-open/

It can detect whether it\'s docked or undocked

function isConsoleOpen() {  
  var startTime = new Date();
  debugger;
  var endTime = new Date();

  return endTime - startTime > 100;
}

$(function() {
  $(window).resize(function() {
    if(isConsoleOpen()) {
        alert(\"You\'re one sneaky dude, aren\'t you ?\")
    }
  });
});


回答9:

The Chrome developer tools is really just a part of WebKit\'s WebCore library. So this question applies to Safari, Chrome, and any other WebCore consumers.

If a solution exists, it\'ll be based off a difference in the DOM when the WebKit web inspector is open and when it\'s closed. Unfortunately, this is a kind of a chicken and egg problem because we can\'t use the inspector to observe the DOM when the inspector is closed.

What you may be able to do is write a bit of JavaScript to dump the entire DOM tree. Then run it once when the inspector is open, and once when the inspector is closed. Any difference in the DOM is probably a side-effect of the web inspector, and we may be able to use it to test if the user is inspecting or not.

This link is a good start for a DOM dumping script , but you\'ll want to dump the entire DOMWindow object, not just document.

Update:

Looks like there\'s a way to do this now. Check out Chrome Inspector Detector



回答10:

Very Reliable hack

Basically set a getter on property and log it in console. Apparently the thing gets accessed only when console is open.

https://jsfiddle.net/gcdfs3oo/44/

var checkStatus;

var element = new Image();
Object.defineProperty(element, \'id\', {
  get:function() {
    checkStatus=\'on\';
    throw new Error(\"Dev tools checker\");
  }
});

requestAnimationFrame(function check() {
    checkStatus = \'off\';
    console.dir(element);
    document.querySelector(\'#devtool-status\').innerHTML = checkStatus;
    requestAnimationFrame(check);
});


回答11:

Also you can try this: https://github.com/sindresorhus/devtools-detect

// check if it\'s open
console.log(\'is DevTools open?\', window.devtools.open);
// check it\'s orientation, null if not open
console.log(\'and DevTools orientation?\', window.devtools.orientation);

// get notified when it\'s opened/closed or orientation changes
window.addEventListener(\'devtoolschange\', function (e) {
    console.log(\'is DevTools open?\', e.detail.open);
    console.log(\'and DevTools orientation?\', e.detail.orientation);
});


回答12:

If you are developers who are doing stuff during development. Check out this Chrome extension. It helps you detect when Chrome Devtoos is opened or closed.

https://chrome.google.com/webstore/detail/devtools-status-detector/pmbbjdhohceladenbdjjoejcanjijoaa?authuser=1

This extension helps Javascript developers detect when Chrome Devtools is open or closed on current page. When Chrome Devtools closes/opens, the extension will raise a event named \'devtoolsStatusChanged\' on window.document element.

This is example code:

 function addEventListener(el, eventName, handler) {
    if (el.addEventListener) {
        el.addEventListener(eventName, handler);
    } else {
        el.attachEvent(\'on\' + eventName,
            function() {
                handler.call(el);
            });
    }
}


// Add an event listener.
addEventListener(document, \'devtoolsStatusChanged\', function(e) {
    if (e.detail === \'OPENED\') {
        // Your code when Devtools opens
    } else {
        // Your code when Devtools Closed
    }
});


回答13:

Some answers here will stop working in Chrome 65. Here\'s a timing attack alternative that works pretty reliably in Chrome, and is much harder to mitigate than the toString() method. Unfortunately it\'s not that reliable in Firefox.

addEventListener(\"load\", () => {

var baseline_measurements = [];
var measurements = 20;
var warmup_runs = 3;

const status = document.documentElement.appendChild(document.createTextNode(\"DevTools are closed\"));
const junk = document.documentElement.insertBefore(document.createElement(\"div\"), document.body);
junk.style.display = \"none\";
const junk_filler = new Array(1000).join(\"junk\");
const fill_junk = () => {
  var i = 10000;
  while (i--) {
    junk.appendChild(document.createTextNode(junk_filler));
  }
};
const measure = () => {
    if (measurements) {
    const baseline_start = performance.now();
    fill_junk();
    baseline_measurements.push(performance.now() - baseline_start);
    junk.textContent = \"\";
    measurements--;
    setTimeout(measure, 0);
  } else {
    baseline_measurements = baseline_measurements.slice(warmup_runs); // exclude unoptimized runs
    const baseline = baseline_measurements.reduce((sum, el) => sum + el, 0) / baseline_measurements.length;

    setInterval(() => {
      const start = performance.now();
      fill_junk();
      const time = performance.now() - start;
      // in actual usage you would also check document.hasFocus()
      // as background tabs are throttled and get false positives
      status.data = \"DevTools are \" + (time > 1.77 * baseline ? \"open\" : \"closed\");
      junk.textContent = \"\";
    }, 1000);
  }
};

setTimeout(measure, 300);

});