Overriding console in an iFrame

Posted on February 02, 2019

This post talks about overriding your console logs in an iFrame on your own domain where you have access to the code inside the iframe.

This might be because you are building a code editor or just executing user code inside an iframe for security reasons.

Our aim is to take the console logs outside the iframe into the main window and process them.

First inside the iframe,

2 // Save the current console log function in case we need it.
3 const _log = console.log;
4 // Override the console
5 console.log = function(...rest) {
6 // window.parent is the parent frame that made this window
7 window.parent.postMessage(
8 {
9 source: 'iframe',
10 message: rest,
11 },
12 '*'
13 );
14 // Finally applying the console statements to saved instance earlier
15 _log.apply(console, arguments);
16 };

Remember to put this before any other JavaScript being executed.

Now, inside our parent code:

1// Listen for messages
2window.addEventListener('message', function(response) {
3 // Make sure message is from our iframe, extensions like React dev tools might use the same technique and mess up our logs
4 if (response.data && response.data.source === 'iframe') {
5 // Do whatever you want here.
6 console.log(response.data.message);
7 }

Overriding other methods.

You can override other console methods by changing up console.log to other functions like console.table

If you want to display the logs, react-inspector is a good place to start.

Happy Coding.