Mir*_*chi 44 html javascript css jquery
iframe的脚本
<script type="text/javascript" >
var a=5;
</script>
Run Code Online (Sandbox Code Playgroud)
父窗口的脚本
<script type="text/javascript" >
function close()
{
var check=document.getElementById("iframeid").contentDocument.a;
alert(check)
}
</script>
Run Code Online (Sandbox Code Playgroud)
我想访问从父级iframe中定义的变量.但是上面的代码不能正常工作,任何人都可以提出实现这个的想法.
Lee*_*unn 55
使用contentWindow
而不是contentDocument
为我工作:
var check = document.getElementById("iframeid").contentWindow.a;
Run Code Online (Sandbox Code Playgroud)
此外,确保域匹配并且您正在使用Web服务器进行测试(从文件系统进行测试时,我收到了协议警告).
小智 17
一种始终可靠地为我工作的方法是iFrame在第一次加载时为其父级提供对其自己的窗口的引用.然后,父级可以通过该引用访问所有变量.这确实需要在iFrame之前加载父级,但对我来说通常就是这种情况.
所以在父母身上
var iFrameWin;
Run Code Online (Sandbox Code Playgroud)
然后在iFrame中加载并安定下来之后的某个时刻
parent.iFrameWin = window; //parent now has a ref to the iframe's window
Run Code Online (Sandbox Code Playgroud)
然后,在父级需要来自iFrame的全局var内容时
alert(iFrameWin.ivar); // shows value if the global 'ivar' in the iFrame
Run Code Online (Sandbox Code Playgroud)
iframe脚本:
var a = 5;
window.parent.postMessage(['varA', a], '*'); // put this in some sort of function, ready, or whatever - you can call it multiple times if you need to as the code in the parent is an eventListener
Run Code Online (Sandbox Code Playgroud)
父窗口的脚本:
var b;
// you might want to write these into if statements to make sure that e.data[0] is varA if you have multiple messages coming across
if (typeof window.addEventListener != 'undefined') {
window.addEventListener('message', function(e) {
b = e.data[1];
}, false);
} else if (typeof window.attachEvent != 'undefined') { // this part is for IE8
window.attachEvent('onmessage', function(e) {
b = e.data; // you'll probably have to play around with this part as I can't remember exactly how it comes across in IE8 -- i think it will involve slice() iirc
});
}
Run Code Online (Sandbox Code Playgroud)
我对此主题的大部分知识来自Ben Vinegar在Seamless iFrames上的演讲
这是一种跨域“可以”的方法来处理这些问题。我敢肯定,就像网络上的任何东西一样,存在一些安全漏洞。
归档时间: |
|
查看次数: |
66622 次 |
最近记录: |