Javascript 查看 Chrome 控制台是否打开

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7798748/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 03:38:09  来源:igfitidea点击:

Find out whether Chrome console is open

javascriptgoogle-chromefirebuggoogle-chrome-devtools

提问by r0skar

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

我正在使用这个小脚本来确定 Firebug 是否打开:

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.

它运作良好。现在找了半个小时想办法检测谷歌浏览器内置的web开发者控制台是否打开,但是没有找到任何提示。

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:

所以似乎无法检测Chrome控制台是否打开。但是有一个“黑客”有效,但有一些缺点:

  • 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!

所以,我现在会选择 Unsigned 的答案,但如果有人提出了一个绝妙的主意,欢迎他仍然回答,我改变选择的答案!谢谢!

采纳答案by Unsigned

requestAnimationFrame (Late 2019)

requestAnimationFrame(2019 年末)

Leaving these previous answers here for historical context. Currently Muhammad Umer's approachworks on Chrome 78, with the added advantage of detecting both close and open events.

将这些先前的答案留在这里以了解历史背景。目前Muhammad Umer 的方法适用于 Chrome 78,具有检测关闭和打开事件的额外优势。

function toString (2019)

函数 toString (2019)

Credit to Overcl9ck's comment on this answer. Replacing the regex /./with an empty function object still works.

感谢Overcl9ck对这个答案的评论。/./用空函数对象替换正则表达式仍然有效。

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

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

regex toString (2017-2018)

正则表达式 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 commenton zswang's answer. This solution takes advantage of the fact that toString()is not called on logged objects unless the console is open.

由于最初的提问者似乎不再存在并且这仍然是公认的答案,因此添加此解决方案以提高可见性。幸得安东宁·希尔德布兰德评论zswangs'的答案。此解决方案利用了toString()除非控制台打开,否则不会在记录的对象上调用的事实。

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)

控制台.profiles (2013)

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

更新:console.profiles已从 Chrome 中删除。此解决方案不再有效。

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

感谢Paul Irish使用探查器从Discover DevTools指出这个解决方案:

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

window.innerHeight (2011)

window.innerHeight (2011)

This other option can detect the docked inspector being opened, afterthe 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');
}

回答by zswang

Chrome 65+ (2018)

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)

演示:https://jsbin.com/cecuzeb/edit?output(2018-03-16 更新)

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

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



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

当打印“Element”Chrome 开发者工具时会得到它的 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);

回答by Sindre Sorhus

I created devtools-detectwhich detects when DevTools is open:

我创建了devtools-detect来检测 DevTools 何时打开:

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.

当 DevTools 未停靠时,它不起作用。但是,适用于 Chrome/Safari/Firefox DevTools 和 Firebug。

回答by Muhammad Umer

Very Reliable hack

非常可靠的黑客

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

基本上在属性上设置一个 getter 并将其记录在控制台中。显然,只有在控制台打开时才能访问该事物。

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

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').className  = checkStatus;
  requestAnimationFrame(check);
});
.on{
  color:limegreen;
}

.off{
  color:red;
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.7.1/css/all.css" integrity="sha256-DVK12s61Wqwmj3XI0zZ9MFFmnNH8puF/eRHTB4ftKwk=" crossorigin="anonymous" />

<p>
  <ul>
    <li>
      dev toolbar open: icon is <span class="on">green</span>
    </li>
    <li>
      dev toolbar closed: icon is <span class="off">red</span>
    </li>
  </ul>
</p>
<div id="devtool-status"><i class="fas fa-7x fa-power-off"></i></div>
<br/>
<p><b>Now press F12 to see if this works for your browser!</b></p>

回答by guya

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.

我找到了一种方法来判断 Chrome 控制台是否已打开。它仍然是一个黑客,但它更准确,并且可以在控制台未停靠或未停靠的情况下工作。

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.

基本上,在关闭控制台的情况下运行此代码大约需要 100 微秒,而在打开控制台时,大约需要两倍的时间,大约 200 微秒。

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

(1 millisecond = 1000 microsecond)

(1 毫秒 = 1000 微秒)

I've written more about it here.

我在这里写了更多关于它的内容。

Demo is here.

演示在这里



Update:

更新:

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

@zswang 找到了当前的最佳解决方案 - 查看他的答案

回答by Robert Moore

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):

如果你的目标是堵塞开发者工具,试试这个(我在一个 JS 代码被混淆的地方找到了一个更复杂的版本,很烦人):

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

回答by huiting Chen

var div = document.createElement('div');
Object.defineProperty(div,'id',{get:function(){
    document.title = 'xxxxxx'
}});

setTimeout(()=>console.log(div),3000)

回答by norlin

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){ ... })

回答by nepjua

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

我写了一篇关于这个的博客文章: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 ?")
    }
  });
});

回答by pepsi

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.

Chrome 开发者工具实际上只是 WebKit 的 WebCore 库的一部分。所以这个问题适用于 Safari、Chrome 和任何其他 WebCore 消费者。

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.

如果存在解决方案,它将基于 WebKit Web 检查器打开和关闭时 DOM 的差异。不幸的是,这是一种鸡和蛋的问题,因为当检查器关闭时,我们无法使用检查器来观察 DOM。

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.

您可以做的是编写一些 JavaScript 来转储整个 DOM 树。然后在检查器打开时运行一次,在检查器关闭时运行一次。DOM 中的任何差异都可能是 Web 检查器的副作用,我们可以使用它来测试用户是否正在检查。

This linkis a good start for a DOM dumping script , but you'll want to dump the entire DOMWindowobject, not just document.

链接是 DOM 转储脚本的良好开端,但您需要转储整个DOMWindow对象,而不仅仅是document.

Update:

更新:

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

看起来现在有一种方法可以做到这一点。查看Chrome Inspector 检测器