2

I have an iframe to which I pass html, css and js content with the srcdoc property and now I would like to log all errors such as syntax etc. I don't need to know if it's syntax or not, I just know if it's error or warning.

I've tried redefining the console.log, console.warn and console.error functions and it works when called explicitly, but not if it's a problem with javascript.

1
  • Please provide enough code so others can better understand or reproduce the problem. Commented Jul 7, 2023 at 6:11

2 Answers 2

1

You have to get the iframe's window using document.querySelector("iframe").contentWindow.

<iframe srcdoc="<script>unassignedFunc()</script>"></iframe>

<script>
    // Get the iframe's window then attach an error handler to the iframe's onerror event
    document.querySelector("iframe").contentWindow.onerror = function(message) {
        // Display error message
        alert(message);
    }
</script>

You can also do a check for other console methods like console.log:

<iframe srcdoc='<script>console.log("I am from the iframe");</script>'></iframe>

<script>
    // Get the iframe's window then manipulate the iframe's console.log
    document.querySelector("iframe").contentWindow.console.log = function() {
        // Display all recurring console.log()
        alert(Array.from(arguments));
    }
</script>
Sign up to request clarification or add additional context in comments.

Comments

1

This should work:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Iframes</title>
  <script>
    // Define the error handler function
    function handleIframeError(message, source, lineno, colno, error) {
      // Log the error information
      console.error('Iframe Error:', message, source, lineno, colno, error);
    }
  </script>
</head>
<body>
  <iframe defer
        title="testFrame"
        srcdoc="
        <script>console.log('Hello world!');</script>
        <p>Hello world!</p>">
    </iframe>

  <script>
    // Attach the error handler to the window.onerror event
    window.onerror = handleIframeError;
  </script>
</body>
</html>

2 Comments

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
It tried using your code and I could only see 'Hello world!' instead of 'Iframe error: ...'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.