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

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

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

这应该可以工作:

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>Iframes</title>
  7. <script>
  8. // 定义错误处理函数
  9. function handleIframeError(message, source, lineno, colno, error) {
  10. // 记录错误信息
  11. console.error('Iframe Error:', message, source, lineno, colno, error);
  12. }
  13. </script>
  14. </head>
  15. <body>
  16. <iframe defer
  17. title="testFrame"
  18. srcdoc="
  19. <script>console.log('Hello world!');</script>
  20. <p>Hello world!</p>">
  21. </iframe>
  22. <script>
  23. // 将错误处理程序附加到window.onerror事件
  24. window.onerror = handleIframeError;
  25. </script>
  26. </body>
  27. </html>
英文:

This should work:

  1. &lt;!DOCTYPE html&gt;
  2. &lt;html lang=&quot;en&quot;&gt;
  3. &lt;head&gt;
  4. &lt;meta charset=&quot;UTF-8&quot;&gt;
  5. &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;
  6. &lt;title&gt;Iframes&lt;/title&gt;
  7. &lt;script&gt;
  8. // Define the error handler function
  9. function handleIframeError(message, source, lineno, colno, error) {
  10. // Log the error information
  11. console.error(&#39;Iframe Error:&#39;, message, source, lineno, colno, error);
  12. }
  13. &lt;/script&gt;
  14. &lt;/head&gt;
  15. &lt;body&gt;
  16. &lt;iframe defer
  17. title=&quot;testFrame&quot;
  18. srcdoc=&quot;
  19. &lt;script&gt;console.log(&#39;Hello world!&#39;);&lt;/script&gt;
  20. &lt;p&gt;Hello world!&lt;/p&gt;&quot;&gt;
  21. &lt;/iframe&gt;
  22. &lt;script&gt;
  23. // Attach the error handler to the window.onerror event
  24. window.onerror = handleIframeError;
  25. &lt;/script&gt;
  26. &lt;/body&gt;
  27. &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:

确定