是否可以检测到用户在IE8-9中打开开发人员工具?

Can I detect the user opening developer tools in IE8-9?

本文关键字:开发 工具 IE8-9 检测 用户 是否      更新时间:2023-09-26

当用户打开开发工具时,是否有某种事件可以检测到?目前我setInterval围绕

的问题
var interval, consoleOpen = false;
interval = setInterval(function() {
    if(typeof console !== 'undefined' && typeof console.log !== 'undefined') {
        clearInterval(interval);
        consoleOpen = true;
        console.log("Console is open!");
        // dump debug message queue...
    }
}, 100);

,但我想避免这样的解决方案,如果我可以,那么有什么更好的方法,我可以使用?这样做的原因是要保留调试消息的积压,并在控制台出现时立即进行console.log()。我已经将消息存储在一个数组中,该数组的工作方式类似于限制为100条消息的队列。

这可能在IE8中不起作用(defineProperty有些bug),但我没有人手来验证这种情况。但是,它在IE9中工作得很好[1]。

(感谢这使得一个不完全完整的解决方案,但它可能是一个有用的起点。)

(function() {
    if ('console' in window) return;
    if (!Object.defineProperty) return;
    Object.defineProperty(window, 'console', {
        configurable: true,
        enumerable: true,
        set: function (val) {
            delete this.console; // 'Unwatch' console changes
            this.console = val;
            // Notify your logging service that it can start
            // outputting to `console.log` here
            // Logger.start() or whatever's appropriate
        }
    });
})();

[1]注意:我并没有真正测试过它,只是把它扔到IE看看会发生什么