0

My index html:

<html>
<head>
    <title>index</title>
    <script src="jquery.js"></script>
</head>
<body>
    <h1>Index</h1>
    <hr/>
    <iframe id="frame"></iframe>
    <hr/>
    <button id="btn">Click</button>

    <script>
    $(function(){

        window.api = {
            fun: function(){alert('index api')}
        };

        var frame = document.getElementById('frame');
        frame.src = 'frame.html';           
    });


    $('#btn').click(function(){
        $('#frame').contents().find('body').css('backgroundColor', 'red');
        $('#frame').contents().find('#btn').text('lol');
    });
    </script>

</body>
</html>

In the loaded frame.html the javascript can acces the api object via parent.api.

Is it possible to add an api object to frame.html window, so it is accessible via window.api there? (and not parent.api) (consider same origin and differnet origins)?

The above code does work (e.g. the #button changing the background and label), but I assume it's because all those documents are on my pc (same origin). Am I right?

2
  • If the iframe is from a different domain, the Same Origin Policy prevents you from accessing it. This is by design. Commented Jul 9, 2013 at 18:35
  • Using Chrome here? Commented Jul 9, 2013 at 18:44

1 Answer 1

1

Assuming you're not running into the same origin policy

var frame = document.getElementById('frame'); // get the frame
frame.addEventListener('load', function () { // only access when loaded
    var win = frame.contentWindow; // get reference to iframe's `window`
    win['foo'] = 'bar'; // set global (within iframe)
});
frame.src = 'frame.html'; // load up page in iframe

If the contents are on a different domain, it's not guaranteed that you will be able to access the <iframe>'s Window even with CORS set up.

The way functions and scope work means they are a bit more difficult to do in the right context, you'd have to either make them generic so it doesn't care or use new win.Function

Sign up to request clarification or add additional context in comments.

1 Comment

Very nice! firstly, will window.foo be available on load in frame.html (i.e. in jquery $(function(){..}); ?? I have just tried and it doesn't seem so, just like the load in parent was launched AFTER the jquery onload code in frame..Secondly, can the iframe access the parent when it comes from a different origin?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.