我有一个 iframe,我使用 srcdoc 属性向其中传递 html、css 和 js 内容,现在我想记录所有错误,例如语法等。我不需要知道它是否是语法,我只知道是否这是错误或警告。
我尝试过重新定义 console.log、console.warn 和 console.error 函数,并且在显式调用时它可以工作,但如果是 javascript 的问题则不行。
这应该有效:
<!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>
您必须使用
document.querySelector("iframe").contentWindow
获取 iframe 的窗口。
<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>
您还可以检查其他控制台方法,例如
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>