英文:
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:
<!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>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论