恢复console.log()

时间:2011-08-17 07:52:36

标签: javascript google-chrome prototypejs console.log

出于某种原因,Magento附带的原型框架(或其他JavaScript代码)正在取代标准的控制台功能,所以我无法调试任何东西。在JavaScript控制台console中写下我得到以下输出:

> console
Object
assert: function () {}
count: function () {}
debug: function () {}
dir: function () {}
dirxml: function () {}
error: function () {}
group: function () {}
groupEnd: function () {}
info: function () {}
log: function () {}
profile: function () {}
profileEnd: function () {}
time: function () {}
timeEnd: function () {}
trace: function () {}
warn: function () {}

我在Linux上使用Google Chrome version 13.0.782.112

Prototype JavaScript framework, version 1.6.0.3

有解决这个问题的快捷方法吗?

8 个答案:

答案 0 :(得分:60)

由于原始控制台位于window.console对象中,请尝试从window.console恢复iframe

var i = document.createElement('iframe');
i.style.display = 'none';
document.body.appendChild(i);
window.console = i.contentWindow.console;
// with Chrome 60+ don't remove the child node
// i.parentNode.removeChild(i);

在Chrome 14上为我工作。

答案 1 :(得分:42)

例如,

delete console.log

还会恢复console.log

console.log = null;
console.log;         // null

delete console.log;
console.log;         // function log() { [native code] }

答案 2 :(得分:12)

Magento在/js/varien/js.js中有以下代码 - 评论出来&它会起作用。

if (!("console" in window) || !("firebug" in console))
{
    var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml",
    "group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];

    window.console = {};
    for (var i = 0; i < names.length; ++i)
        window.console[names[i]] = function() {}
}

答案 3 :(得分:7)

delete window.console恢复Firefox和Chrome中的原始console对象。

这是如何工作的? window是一个托管对象,通常在所有实例之间使用通用原型实现(浏览器中有许多选项卡)。

外部库/框架(或Firebug等)的一些愚蠢的开发人员覆盖window实例的属性控制台,但它不会破坏window.prototype。通过delete运算符,我们将从console.*方法调度到原型代码。

答案 4 :(得分:3)

在脚本开头的变量中保存对原始console的引用,然后使用此引用,或重新定义console以指向捕获的值。

示例:

var c = window.console;

window.console = {
    log :function(str) {
        alert(str);
    }
}

// alerts hello
console.log("hello");

// logs to the console
c.log("hello");

答案 5 :(得分:0)

此问题中给出的解决方案不再能在新浏览器中正确解决此问题。唯一一个(有点)工作是从@ {xereress所说的<iframe>抓住控制台。

我编写了一个用户脚本,可以保护控制台不被覆盖。它不会破坏任何覆盖控制台的工具 - 它会调用被覆盖的和原始的方法。它当然也可以包含在网页中。

// ==UserScript==
// @name        Protect console
// @namespace   util
// @description Protect console methods from being overriden
// @include     *
// @version     1
// @grant       none
// @run-at      document-start
// ==/UserScript==
{

    /**
      * This object contains new methods assigned to console.
      * @type {{[x:string]:Function}} **/
    const consoleOverridenValues = {};
    /**
      * This object contains original methods copied from the console object
      * @type {{[x:string]:Function}} **/
    const originalConsole = {};
    window.originalConsole = originalConsole;
    // This is the original console object taken from window object
    const originalConsoleObject = console;
    /**
     * 
     * @param {string} name
     */
    function protectConsoleEntry(name) {
        const protectorSetter = function (newValue) {
            originalConsole.warn("Someone tried to change console." + name + " to ", newValue);
            consoleOverridenValues[name] = function () {
                /// call original console first
                originalConsole[name].apply(originalConsoleObject, arguments);
                if (typeof newValue == "function") {
                    /// call inherited console
                    newValue.apply(window.console, arguments);
                }
            }
        }
        const getter = function () {
            if (consoleOverridenValues[name])
                return consoleOverridenValues[name];
            else
                return originalConsole[name];
        }
        Object.defineProperty(console, name, {
            enumerable: true,
            configurable: false,
            get: getter,
            set: protectorSetter
        });
    }

    /*
     *** This section contains window.console protection
     *** It mirrors any properties of newly assigned values
     *** to the overridenConsoleValues
     *** so that they can be used properly
    */

    /** 
      * This is any new object assigned to window.console
      * @type {Object} **/
    var consoleOverridenObject = null;
    /// Separate boolean is used instead
    /// of checking consoleOverridenObject == null
    /// This allows null and undefined to be assigned with 
    /// expected result
    var consoleIsOverriden = false;

    for (var i in console) {
        originalConsole[i] = console[i];
        protectConsoleEntry(i);
    }

    Object.defineProperty(window, "console", {
        /// always returns the original console object
       /// get: function () { return consoleIsOverriden ? consoleOverridenObject : originalConsoleObject; },
        get: function () { return originalConsoleObject; },
        set: function (val) {
            originalConsole.log("Somebody tried to override window.console. I blocked this attempt."
                + " However the emulation is not perfect in this case because: \n"
                + "     window.console = myObject;\n"
                + "     window.console == myObject\n"
                + "returns false."
            )
            consoleIsOverriden = true;
            consoleOverridenObject = val;

            for (let propertyName in val) {
                consoleOverridenValues[propertyName] = val[propertyName];
            }
            return console;
        },
    });
}

答案 6 :(得分:0)

function restoreConsole() {
  // Create an iframe for start a new console session
  var iframe = document.createElement('iframe');
  // Hide iframe
  iframe.style.display = 'none';
  // Inject iframe on body document
  document.body.appendChild(iframe);
  // Reassign the global variable console with the new console session of the iframe 
  console = iframe.contentWindow.console;
  window.console = console;
  // Don't remove the iframe or console session will be closed
}

在Chrome 71和Firefox 65上进行了测试

答案 7 :(得分:0)

以防万一有人遇到同样的情况。 我没有回答Xaerxess的原始答案,因为我没有足够的声誉来做到这一点。 看起来这是正确的答案,但是由于某种原因,我注意到有时它可以在我的软件中工作,有时却不行。

因此,我尝试在运行脚本之前完成删除操作,并且看起来一切都可以100%正常地工作。

if (!("console" in window) || !("firebug" in console))
{

  console.log = null;
  console.log;         // null

  delete console.log;

  // Original by Xaerxess
  var i = document.createElement('iframe');
  i.style.display = 'none';
  document.body.appendChild(i);
  window.console = i.contentWindow.console;

}

谢谢大家。

相关问题