最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Override console methods (log, warn, error) of an iframe - Stack Overflow

programmeradmin7浏览0评论

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')}
    />
发布评论

评论列表(0)

  1. 暂无评论