如何从外部来源捕获 console.log?

How to capture console.log from external sources?

我了解如何修改 console.log 函数来拦截日志并将其推送到数组中。但是,这似乎不适用于所有控制台日志。在我的 html 中,我加载了一个 html 网络应用程序 (\creative0x600 with video\index.html),它还执行了一个 console.log("click detected"),我可以在我的 chrome 开发工具中看到它,但是未被控制台捕获。 ogs(代码示例中的第二个脚本)。我怀疑因为这是一个正在加载的外部文件,所以我无法拦截它。

是否有从任何来源获取所有 console.log 并保存的解决方案?

<!DOCTYPE html>
<head>
<script>

//add index.html to div on click

function load_home() {
    console.log("Loaded");
    document.getElementById("content").src='creative\300x600 with video\index.html';

}
window.addEventListener("click",load_home);
</script>
<script>

//modify console.log

console.defaultLog = console.log.bind(console);
console.logs = [];
console.log = function() {
    console.defaultLog.apply(console, arguments);
    console.logs.push(Array.from(arguments));
};
    </script>
</head>
<html>
<iframe id="content" style="width: 300px; height:600px; background-color:blue"  ></iframe>
</body>
</html>

编辑:

尝试在 div 而不是 iframe 中制作它,同样的问题是无法记录外部 html 的 console.log。只有 load_home 函数的 console.log("loaded") 会被记录。

<!DOCTYPE html>
<head>

<script>
function load_home() {
    console.log("Loaded");
     document.getElementById("content").innerHTML='<object type="text/html" data="creative\300x600 with video\index.html" ></object>';


}
window.addEventListener("click",load_home);
</script>
<script>
console.defaultLog = console.log.bind(console);
console.logs = [];
console.log = function() {
    console.defaultLog.apply(console, arguments);
    console.logs.push(Array.from(arguments));
};
    </script>
</head>
<html>


<div id="content" style="width: 300px; height:600px; z-index:-1;" ,"onclick=load_home();" </div>

</body>
</html>

这里的问题是因为 iframeiframe 有一个不同的 window 对象,独立于父对象的 window 对象。这意味着您对父级 window.console 所做的任何修改都不会影响 iframe 的 window.console.

您可以通过 contentWindow 获取框架的 window 对象并修改其 console。但是您必须为每个现在 和未来 iframe 执行此操作。此外,您无法访问从另一个域呈现页面的 iframe 的 contentWindow

如果您试图捕获所有帧的日志并以某种方式将它们合并到一个大日志中,更好的选择是在您要跟踪的每个页面上使用相同的 console-altering 脚本。然后将所有日志发送到服务器,按时间戳或其他顺序排序。这几乎就是 Sentry 的工作原理。