I pass javascript code to an iframe and run it inside a eval function. With the eval I avoid the limit for large amount of code when the code contains libraries like React and ReactDOM. I got to redefine predefined console.log to send to the parent the message, but I am missing the line of code where the console is executed.
Script inside the iframe
<script>
const _log = console.log;
console.log = function (...args) {
// Send to parent
window.parent.postMessage(
{
id: '${id}',
source: 'code-preview',
message: args,
},
'*',
);
_log.apply(console, args);
};
window.addEventListener('message', (event) => {
const handleError = (error) => {
const root = document.getElementById('root');
root.innerHTML = '<div style="color: red;">' + error + '</div>';
console.error(error);
};
window.addEventListener('error', (event) => {
event.preventDefault();
handleError(event.error)
});
try {
eval(event.data)
} catch(error){
if(error instanceof Error){
return {
code: '',
error: error.message
}
} else {
throw error;
}
}
}, false);
</script>
I tried with new Error().stack
but because is executed inside eval, I only got the line of eval. Any idea if sent the correct line to the parent is executed? The ideal solution is something like this.
import React from 'react';
console.log('Hello word'); // line 3