Javascript 将变量添加到iframe';全球范围

Javascript 将变量添加到iframe';全球范围,javascript,html,iframe,cors,Javascript,Html,Iframe,Cors,我的索引html: <html> <head> <title>index</title> <script src="jquery.js"></script> </head> <body> <h1>Index</h1> <hr/> <iframe id="frame"></iframe> <

我的索引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>

指数
指数


点击 $(函数(){ window.api={ 乐趣:函数(){alert('index-api')} }; var frame=document.getElementById('frame'); frame.src='frame.html'; }); $('#btn')。单击(函数(){ $('#frame').contents().find('body').css('backgroundColor','red'); $('#frame').contents().find('#btn').text('lol'); });
在加载的
frame.html
中,javascript可以通过
parent.api
访问
api
对象

是否可以将api对象添加到frame.html窗口,以便通过
window.api
访问?(而不是
parent.api
)(考虑相同来源和不同来源)


上面的代码确实有效(例如,
#按钮
更改背景和标签),但我认为这是因为所有这些文档都在我的电脑上(同一来源)。我说得对吗?

假设您没有遇到相同的原产地政策

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
如果内容位于不同的域中,即使设置了CORS,也不能保证您能够访问
的窗口


函数和作用域的工作方式意味着它们在正确的上下文中更难执行,您必须使它们成为通用的,这样它才不在乎,或者使用
new win.Function

如果iframe来自不同的域,则同源策略会阻止您访问它。这是设计的。在这里使用?很好!首先,
window.foo
是否可以在frame.html中加载(即在jquery
$(function(){..});
?我刚刚尝试过,但似乎不是这样,就像在jquery onload code in frame之后启动父级中的
load
一样。其次,当iframe来自不同的来源时,它可以访问父级吗?