samdenty / console-feed

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

Getting console logs from iframe error #67

Closed Foscat closed 4 years ago

Foscat commented 4 years ago

I am trying to get the logs from an iframe and have run into several major issues. I have not been able to find a example of getting logs from one anywhere, so I found a way to get them but I am not sure it is the proper way. That leads to my core issue is getting the Hook() to work correctly. It will either never run or it will run in a infinite loop. Here is the component I am making to show the iframe and the logs below. I have a operation in the setLogs hook to prevent the endless empty data arrays from being added to the state.

Here is a video I made of the error and how it happens. https://drive.google.com/file/d/1qtrsCLr8RTC1TirnpXKuGkDkwVpfTRL4/view

My React Component:

` import React, { useState, useEffect } from "react"; import { Hook, Console, Decode, Unhook } from "console-feed"; import SplitPane from "components/SplitPane/SplitPane";

const WebViewer = ({ webTemplate }) => { const [contentRef, setContentRef] = useState(null);

const useFrameObject = () => { const [logs, setLogs] = useState([]); const frameData = contentRef?.contentWindow?.console;

useEffect(() => {
  function grabConsoleData() {
    console.log("grab console data", frameData);
    if (frameData) {
      Hook(frameData, (log) =>
        setLogs((curLogs) =>
          log[0].data.length ? [...curLogs, Decode(log)] : [...curLogs]
        )
      );
      console.log("hook ran now unhook");
      return () => Unhook(contentRef);
    }
  }

  // For some reason the loop will not run unless this function is called but is always a undefined value so I have it called as a unused varible
  // eslint-disable-next-line
  let foundLog = frameData?.feed?.pointers.log();
  console.log("add"); // To keep track of when event listener is added
  document
    .getElementById("webPreviewFrame")
    .addEventListener("load", grabConsoleData);

  grabConsoleData();

  return () => {
    console.log("remove");// To keep track of when the event listener is removed
    document
      .getElementById("webPreviewFrame")
      .removeEventListener("load", grabConsoleData);
  };
}, [frameData]); // If I have a dependency array it never catches logs, without it logs appear in logs state but endless loop
console.log("return logs", logs);
return logs;

};

return (