如何访问iframe中的数据?

时间:2016-10-16 13:18:38

标签: javascript php html codeigniter iframe

我一直在尝试从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();但没有运气。

1 个答案:

答案 0 :(得分:1)

对于您的问题已经有很多答案,google“在iframe中访问DOM”可以获得多个解决方案,here is one

一般情况下,如果出于安全原因将iframe加载到其他域上,那么无法访问iframe数据(否则想象来自Facebook的“赞”小部件,您可以加载它然后窃取访问您网站的用户的授权cookie ...)

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

相关问题