I want to override console methods (e.g. log, warn, error) of an iframe.
I get the error: webrtc/offer: stream not found in the console from the iframe.
I am trying to override console methods (log, warn, error) so that they does their original job in addition to storing all the method call arguments in a React State variable - consoleOutput
.
But the data in consoleOutput
is always empty. Any idea why I am unable to override those methods?
My code:
const iframeRef = useRef<HTMLIFrameElement | null>(null)
const [consoleOutput, setConsoleOutput] = useState<string[]>([])
useEffect(() => {
if (iframeRef.current) {
const iframeWindow = iframeRef.current.contentWindow as any;
if (iframeWindow) {
const originalConsole = iframeWindow.console;
const newConsoleOutput: string[] = [];
const wrapConsoleMethod = (method: keyof Console, prefix: string) => {
return (...args: any[]) => {
newConsoleOutput.push(`[${prefix}] ` + args.map(String).join(" "));
setConsoleOutput([...newConsoleOutput]);
originalConsole[method](...args);
};
};
iframeWindow.console = {
...originalConsole,
log: wrapConsoleMethod("log", "Log"),
error: wrapConsoleMethod("error", "Error"),
warn: wrapConsoleMethod("warn", "Warn"),
};
}
}
}, []);
<div>
<h3>Console output from iframe::</h3>
<pre>{consoleOutput.join('\n')}</pre>
</div>
<iframe
ref={iframeRef}
src={iframeSrc}
onLoad={() => console.warn('iframe loaded')}
/>