javascript 捕获 iframe 的控制台日志

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14924362/
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-10-26 22:56:48  来源:igfitidea点击:

Capture console log of an iframe

javascriptiframeconsole

提问by Adonis K. Kakoulidis

Is there a way to capture the console outside of an iframe?

有没有办法在 iframe 之外捕获控制台?

I'm working on an online IDEsimilar to jsFiddle and I wanted to give the users to option to at least read the results of the javascript console.

我正在开发一个类似于 jsFiddle的在线 IDE,我想让用户选择至少读取 javascript 控制台的结果。

采纳答案by SeanJM

Here is another solution if you don't want to append to HTML

如果您不想附加到 HTML,这是另一种解决方案

var console = {
  __on : {},
  addEventListener : function (name, callback) {
    this.__on[name] = (this.__on[name] || []).concat(callback);
    return this;
  },
  dispatchEvent : function (name, value) {
    this.__on[name] = (this.__on[name] || []);
    for (var i = 0, n = this.__on[name].length; i < n; i++) {
      this.__on[name][i].call(this, value);
    }
    return this;
  },
  log: function () {
    var a = [];
    // For V8 optimization
    for (var i = 0, n = arguments.length; i < n; i++) {
      a.push(arguments[i]);
    }
    this.dispatchEvent("log", a);
  }
};

Outside the iframe

iframe 之外

iframe.contentWindow.console.addEventListener("log", function (value) {
  console.log.apply(null, value);
});

回答by A. Rodas

If you want to print the log messages inside the window container's body, it is possible to declare the panel there:

如果你想在窗口容器的主体内打印日志消息,可以在那里声明面板:

var console = {
    panel: $(parent.document.body).append('<div>'),
    log: function(m){
        this.panel.prepend('<div>'+m+'</div>');
    }       
};
console.log('message');