Karthi Keyan
Karthi Keyan

Reputation: 4393

How to access the variable in iframe which contain another html?

I'm using iframe test in my test.html. Another test2.html file is loaded in that iframe test, i need to access the variable's which is used in the test2.html. Is there any way to access that in the test.html.

Here is my Samples

test.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <link href="Styles/redmond/jquery-ui-1.10.3.custom.css" rel="stylesheet" />
    <script src="Js/jquery-1.9.1.js" type="text/javascript"></script>
    <script src="Js/jquery-ui-1.10.3.custom.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function(){
           //this code is doesn't work
           var data1= document.getElementById('test').contentWindow.document.data;
        });
    </script>
    <style type="text/css">
        body,html{
            height:100%;
            width:100%;
            top:0;
            left:0;
            overflow:auto;
        }
        #test{
            height:250px;
            width:250px;
            border:1px solid gray;
        }
    </style>
</head>
<body>
    <iframe id="test" src="test2.html"></iframe>
</body>
</html>

test2.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <link href="Styles/redmond/jquery-ui-1.10.3.custom.css" rel="stylesheet" />
    <script src="Js/jquery-1.9.1.js" type="text/javascript"></script>
    <script src="Js/jquery-ui-1.10.3.custom.js" type="text/javascript"></script>
    <script type="text/javascript">
        var data = 'This data is retrived from test2.html';
        $(document).ready(function () {
            $('#div')[0].textContent = data;
        });
    </script>
    <style type="text/css">
        body,html{
            height:100%;
            width:100%;
            top:0;
            left:0;
            overflow:auto;
        }
        #div{
            height:50px;
            width:200px;
            border:1px solid gray;
            margin:10px;
        }
    </style>
</head>
<body>
    <div id="div">Hello</div>
</body>
</html>

Any suggestions should be appreciated...!

Upvotes: 1

Views: 3848

Answers (1)

putvande
putvande

Reputation: 15213

As mentioned you should get the variable from contentWindow instead of contentWindow.document. And also, you might need to wait for the iframe to load.

$(document).ready(function(){
     $('#test').on('load',function(){           
          var data1 = $('#test').get(0).contentWindow.data;
          // Or plain JavaScript
          // var data1 = document.getElementById('test').contentWindow.data;
     });
});

Upvotes: 1

Related Questions