如何知道在加载包含srcdoc的iframe时是否存在错误?

huangapple go评论79阅读模式
英文:

How can I know if there are errors when loading an iframe with srcdoc?

问题

我有一个iframe,通过srcdoc属性传递html、css和js内容,现在我想记录所有错误,比如语法错误等。我不需要知道是语法错误还是其他错误,我只需要知道是否有错误或警告。

我尝试重新定义console.log、console.warn和console.error函数,当显式调用时它可以工作,但如果是javascript的问题就不行。

英文:

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

得分: 1

这应该可以工作:

<!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>
        // 定义错误处理函数
        function handleIframeError(message, source, lineno, colno, error) {
            // 记录错误信息
            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>
        // 将错误处理程序附加到window.onerror事件
        window.onerror = handleIframeError;
    </script>
</body>
</html>
英文:

This should work:

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

  &lt;script&gt;
    // Attach the error handler to the window.onerror event
    window.onerror = handleIframeError;
  &lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;

huangapple
  • 本文由 发表于 2023年7月6日 17:39:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/76627477.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定