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?

Kiel
  • 271
  • 3
  • 10

1 Answers1

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

Paul S.
  • 64,864
  • 9
  • 122
  • 138
  • 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? – Kiel Jul 09 '13 at 19:27