3

I have an iframe on my page:

<iframe></iframe>

And there's a div on my page where I'd like to show the javascript console for it:

<div id='console'></div>

So in the iframe, if a script did: console.log("hello world");

it would show in my console div.

Is there a way to do this? Also, I don't want to open developer tools. I want the console to be shown as part of my page within the html.

Jaykumar Patel
  • 26,836
  • 12
  • 74
  • 76
Shai UI
  • 50,568
  • 73
  • 204
  • 309
  • 1
    Is iframe on the same domain? – dfsq Mar 15 '15 at 19:46
  • Why do you want to use default `console` functionality? Can't you write own console instead? – Damian Polac Mar 15 '15 at 19:50
  • As for the second part of your question - displaying the output of `console.log` on the page, perhaps this might be useful: [how can I override console.log()...](http://stackoverflow.com/questions/16259711/how-can-i-override-console-log-and-append-a-word-at-the-beginning-of-the-outpu) – Lix Mar 15 '15 at 19:50
  • possible duplicate: http://stackoverflow.com/questions/7961229/is-there-a-way-to-change-context-to-iframe-in-javascript-console – kasper Taeymans Mar 15 '15 at 19:51
  • I want a cross browser solution. So that didn't answer my question. – Shai UI Mar 15 '15 at 19:53
  • you can use `cd` in dev tools. – chiliNUT Mar 15 '15 at 20:11

1 Answers1

1

You can get the console value in your HTML entity.

<iframe id="xyz"></iframe>

var iframeWindow = document.getElementById("xyz").contentWindow;

iframeWindow.console.log = function(val) {
    var divId = document.getElementById("console");
    var span = document.createElement("span");
    span.appendChild(document.createTextNode(val));
    divId.appendChild(span);
};

this will get all the console.log of the iframe and append to the div

Suraj
  • 31
  • 3
  • 1
    This doesn't work. You can override the `iframeWindow.console.log` function, but doing so doesn't change anything. – Lewy Blue Sep 25 '19 at 05:22