31

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

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

Adonis K. Kakoulidis
  • 4,951
  • 6
  • 34
  • 43
  • 3
    You can overwrite `console.log` as suggested [here](http://stackoverflow.com/questions/11049996/redirect-calls-to-console-log-to-standard-output-in-jasmine-tests#11050414) – A. Rodas Feb 17 '13 at 18:27
  • 1
    Won't that print the results in the iframe's content? I'd like to print the console logs in a div inside the iframe container's body – Adonis K. Kakoulidis Feb 17 '13 at 18:46

3 Answers3

24

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');
A. Rodas
  • 20,171
  • 8
  • 62
  • 72
  • Hi, thanks it works as expected but could you please explain what this line does? `panel: $(parent.document.body).append('
    '),`, I don't understand why we use the `.append('div')` part.
    – Adonis K. Kakoulidis Feb 17 '13 at 23:01
  • That's only for wrapping the messages into a single `div`. You can use `panel: $(parent.document.body)` too, but then you'll have each message directly as a child of the container's body. – A. Rodas Feb 17 '13 at 23:19
  • 1
    Ya after a while i understood its purpose and modified it to fit my needs, thanks for taking the time to explain it to me. – Adonis K. Kakoulidis Feb 18 '13 at 03:45
15

Here is another solution if you don't want to append to 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.contentWindow.console.addEventListener("log", function (value) {
  console.log.apply(null, value);
});
SeanJM
  • 176
  • 1
  • 7
11

You can use Chrome DevTools. There is a Javascript Selector "Top" where you can select the source. The logs from that source will show up.

Chrome DevTools Javascript Context Selector

Matt
  • 1,388
  • 15
  • 16