3

是否有某种事件可以用来检测用户何时打开开发者工具?目前我 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 条消息的队列。

4

1 回答 1

2

这在 IE8 中可能不起作用(defineProperty有点错误),但我没有手头来验证情况。但是,它在 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 上看看会发生什么,我还没有实际测试过它。

于 2013-04-25T11:04:17.193 回答