samdenty / console-feed

Captures console.log's into a React Component 🔥
https://stackblitz.com/~/github.com/samdenty/console-feed
MIT License
649 stars 106 forks source link

How to access iframe console in React using hooks #98

Open Arshanshagarwal opened 2 years ago

Arshanshagarwal commented 2 years ago

Context - I wanted to capture the console of the iframe element I have created and use those logs to showcase a console in the browser

Code -

import React, { useState, useEffect } from 'react'
import { Console, Hook, Unhook } from 'console-feed'

const LogsContainer = ({iframeRef}) => {
  const [logs, setLogs] = useState([])

  // run once!
  useEffect(() => {
    Hook(
      iframeRef.current.contentWindow.console,
      (log) => setLogs((currLogs) => [...currLogs, log]),
      false
    )
    return () => Unhook(iframeRef.current.contentWindow.console)
  }, [])

  return <Console logs={logs} variant="dark" />
}

export { LogsContainer } 

Issue - I tried using Reference of iFrame to access the console, by passing the iframRef from the main code to the Hook and unhooking the same after using it. But it does not work, my logs state that was returned didn't have any elements in it. I tried using the same code for window.console, and it worked perfectly fine.

How could I use it?

isaacking5 commented 2 years ago

The same case has also come up for me, does anyone have any ideas how to work around it?

Please let me know