【问题标题】:How to access data within an iframe?如何访问 iframe 中的数据?
【发布时间】:2016-10-16 13:18:38
【问题描述】:

我一直在尝试从 iframe 访问数据。我正在研究codeigniter。我花了一整天的时间寻找解决方案,但没有运气。我不是javascript专家,所以对我来说变得越来越难。请看我的代码。

home-upload-dialog.php查看文件

<div id="popup-contents">
    <iframe id="upload-frame" frameborder="0" scrolling="no" height="200" width="100%" src="<?php echo site_url('home/upload_area/' . $_REQUEST['count']);?>"></iframe>
</div>
<input type="button" value="click me" onclick="run()">
<script>
    run() {
        var iframedoc = document.getElementsByTagName('iframe')[0].contentWindow.document;
        var inputs = iframedoc.getElementById('text');
        console.log(inputs);
    }
</script>

home.php控制器

upload_area() {
    $data['count'] = $count;
    $this->load->view('upload-area', $data);
}

upload-area.php查看文件

<!DOCTYPE html>
    <html>
    <head>
        <title>Title here</title>
    </head>
    <body>
        <input type="text" name="text" id="text" value="someValue">
    </body>
    </html>

我收到错误消息Uncaught TypeError: Cannot read property 'contentWindow' of undefined 我可能忽略了一些事情。任何帮助将不胜感激!

我也尝试了$('iframe').contents().find('#text').html();,但没有成功。

【问题讨论】:

  • 我已经访问过该页面,但仍然遇到同样的问题。
  • 只是一个提示,几天前我试图解决一个网络界面(使用框架)的问题,我使用了window.frames['name_of_the_frame'].document
  • 它仍然显示cannot read property 'document' of undefined 我的代码中可能存在一些愚蠢的小错误。但是我尝试了很多选择都没有结果。
  • 你的iframe 需要有一个name 属性。

标签: javascript php html codeigniter iframe


【解决方案1】:

你的问题已经有很多答案了,google "access DOM inside iframe" 有几个解决方案,here is one。

通常请记住,如果出于安全原因将 iframe 加载到另一个域中,您无法访问 iframe 数据(否则想象一下来自 Facebook 的“Like”小部件,您可以加载它然后窃取访问您网站的用户的授权 cookie...)

编辑:请注意,上面的安全限制包括有趣的情况,例如您的网站是从“www.domain.com/page.php”加载的,而您的 iframe 是从“domain.com/iframe.php”加载的",所以检查一下。

【讨论】:

  • 不要将答案指向回答完全相同问题的问题,而是将问题标记为重复。
  • @CharlotteDunois 感谢您的提示,我是新来的 :)
  • 你能解释一下另一个域是什么意思吗?
  • 在加载 iframe 的页面上使用“查看源代码”,并将
  • 哦,好吧。所以它在同一个域中,我仍然收到错误。有什么解决办法吗?
猜你喜欢
  • 2012-08-18
  • 2020-03-07
  • 1970-01-01
  • 2015-04-27
  • 1970-01-01
  • 1970-01-01
  • 2019-06-15
  • 1970-01-01
  • 2012-12-29
相关资源
最近更新 更多