如何从 iframe 从控制台捕获日志?



我想在控制台中获取来自我的iFrame标签的日志并将其显示在另一个元素中。

window.console = {
log: function(str){
let node = document.createElement("li");
node.appendChild(document.createTextNode(str));
document.getElementById("consoleMsgHere").appendChild(node);
}
}

此代码能够从文档中获取常用控制台,但无法从 iframe 标记中捕获日志。

任何帮助将不胜感激。

这是一个非常基本的例子。唉,由于 iframe 限制,我无法提供片段。因此,这更像是一个复制 pate-to-dekstop的例子。

基本上,我将log()更改为window.top.postMessage(),并在window.topmessage上添加一个侦听器来处理传入的消息。有关更多详细信息,请参阅文档。

<html>
<head>
<script>
//REM: Overwriting console.log()
window.console = {
log: function(str){
//REM: Forward the string to the top window.
//REM: https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage
window.top.postMessage(str, '*');
}
};
//REM: Listening to messages
window.addEventListener('message', function(event){
//REM: Just appending it to the body.. lazy
document.body.appendChild(document.createTextNode(event.data))
}, false);
//REM: Just required for the demo..
window.onload = function(){
if(window.top !== window.self){
//REM: Changing the color of the body to distinguish iframe and not iframe
document.body.style.background = 'limegreen'
}
else{
//REM: Adding itself as an iframe to demostrate the logic while being lazy
document.body.appendChild(document.createElement('iframe')).src = window.location.href
}
}
</script>
</head>
<body>
<input type = 'text' value = 'test' onchange = 'console.log(this.value)' />
</body>
</html>

最新更新