2

I'm trying to catch console logs of an iframe which I don't have access to its source and its implementation.

 <iframe src="an http address" name="my-iframe"  allowFullScreen/>

When the iframe logs data I see them in my console. But the problem is,

this piece of code

// define a new console
var console = (function(oldCons){
    return {
        log: function(text){
            oldCons.log(text);
            if(text === "hi"){
              alert("text")
            }
        },
        info: function (text) {
            oldCons.info(text);
            if(text === "hi"){
              alert("text")
            }
        },
        warn: function (text) {
            oldCons.warn(text);
            if(text === "hi"){
              alert("text")
            }
        },
        error: function (text) {
            oldCons.error(text);
            if(text === "hi"){
              alert("text")
            }
        }
    };
}(window.console));

//Then redefine the old console
window.console = console;

Which I got from this post is not working for the iframe logs. It only works on my app console logs.

Arian Shahalami
  • 1,369
  • 2
  • 13
  • 25

1 Answers1

2

If the src is a different domain, and you can't run code directly on the other domain (for example, by being able to modify or insert a .js into it), then there's nothing you can do. This is for security reasons: browsers don't want to leak any information between domains unless the sender of the information deliberately allows it.

If you can alter code on the other domain, you could monkeypatch the console and have it pass the log information to the parent window with postMessage so that the parent can do something with it.

If you happen to be trying to examine messages for your personal use only (rather than for use by random people on the internet), you can modify your browser to run your custom JavaScript on the other domain with a userscript, by using a userscript manager like Tampermonkey.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • yes it's in a different domain which I dont have access to it. so u are saying i can do nothing with my iframe's logged data in my console?? – Arian Shahalami Dec 16 '20 at 16:30
  • 1
    Correct, there isn't anything you can do with it, other than clear the entire console from the parent page. The log messages go directly from the embedded iframe to the browser console; they don't go through the parent site, so if the only code you can change is on the parent site, you won't be able to examine or change logging behavior of the iframe. – CertainPerformance Dec 16 '20 at 16:34