【问题标题】:How to show javascript console for an iframe?如何显示 iframe 的 javascript 控制台?
【发布时间】:2015-03-15 19:45:29
【问题描述】:

我的页面上有一个 iframe:

<iframe></iframe>

我的页面上有一个 div,我想在其中显示 javascript 控制台:

<div id='console'></div>

所以在 iframe 中,如果脚本这样做了: console.log("hello world");

它会显示在我的控制台 div 中。

有没有办法做到这一点?另外,我不想打开开发者工具。我希望控制台在 html 中显示为我的页面的一部分。

【问题讨论】:

  • iframe 是否在同一个域中?
  • 为什么要使用默认的console 功能?你不能写自己的控制台吗?
  • 至于你问题的第二部分——在页面上显示console.log 的输出,也许这可能有用:how can I override console.log()...
  • 我想要一个跨浏览器的解决方案。所以这并没有回答我的问题。

标签: javascript html


【解决方案1】:

您可以在 HTML 实体中获取控制台值。

<iframe id="xyz"></iframe>

var iframeWindow = document.getElementById("xyz").contentWindow;

iframeWindow.console.log = function(val) {
    var divId = document.getElementById("console");
    var span = document.createElement("span");
    span.appendChild(document.createTextNode(val));
    divId.appendChild(span);
};

这将获取 iframe 的所有 console.log 并附加到 div

【讨论】:

  • 这不起作用。您可以覆盖iframeWindow.console.log 函数,但这样做不会改变任何内容。
猜你喜欢
  • 1970-01-01
  • 2012-11-21
  • 2023-02-25
  • 1970-01-01
  • 2015-05-03
  • 2018-01-16
  • 1970-01-01
  • 2017-01-19
  • 1970-01-01
相关资源
最近更新 更多