我想从iframe调用父窗口JavaScript函数。
<script>
function abc()
{
alert("sss");
}
</script>
<iframe id="myFrame">
<a onclick="abc();" href="#">Call Me</a>
</iframe>
我想从iframe调用父窗口JavaScript函数。
<script>
function abc()
{
alert("sss");
}
</script>
<iframe id="myFrame">
<a onclick="abc();" href="#">Call Me</a>
</iframe>
当前回答
最近,我不得不找出为什么这种方法也不起作用。
你想从子iframe调用的javascript需要在父iframe的头部。如果它在主体中,则脚本在全局作用域中不可用。
<head>
<script>
function abc() {
alert("sss");
}
</script>
</head>
<body>
<iframe id="myFrame">
<a onclick="parent.abc();" href="#">Click Me</a>
</iframe>
</body>
希望这能帮助到再次遇到这个问题的人。
其他回答
一个插件助手的要点,允许父窗口调用子iframe窗口函数,反之亦然,但所有的调用都是异步的。
https://gist.github.com/clinuxrulz/77f341832c6025bf10f0b183ee85e072
这也可以跨原点工作,但只能调用从父窗口导出到iframe的函数,并且父窗口只能调用iframe导出的函数。
使用Firefox和Chrome浏览器,您可以使用:
<a href="whatever" target="_parent" onclick="myfunction()">
如果myfunction同时出现在iframe和parent中,父函数将被调用。
Window.postMessage ()
这种方法可以安全地实现跨源通信。
如果你可以访问父页代码,那么任何父方法都可以被调用,任何数据都可以直接从Iframe中传递。这里有一个小例子:
父页面:
if (window.addEventListener) {
window.addEventListener("message", onMessage, false);
}
else if (window.attachEvent) {
window.attachEvent("onmessage", onMessage, false);
}
function onMessage(event) {
// Check sender origin to be trusted
if (event.origin !== "http://example.com") return;
var data = event.data;
if (typeof(window[data.func]) == "function") {
window[data.func].call(null, data.message);
}
}
// Function to be called from iframe
function parentFunc(message) {
alert(message);
}
Iframe代码:
window.parent.postMessage({
'func': 'parentFunc',
'message': 'Message text from iframe.'
}, "*");
// Use target origin instead of *
更新:
安全注意事项:
如果您知道其他窗口的文档应该位于何处,则始终提供特定的targetOrigin,而不是*。未能提供特定的目标会泄露你发送到任何感兴趣的恶意网站的数据(由ZalemCitizen评论)。
引用:
跨文档信息 Window.postMessage () 我可以用
这是为有需要的人准备的。如果它们使用不同的协议,Ash Clarke的解决方案就不起作用,所以如果您使用SSL,请确保您的iframe也使用SSL,否则将破坏功能。他的解决方案确实适用于域名本身,所以谢谢你。
Ash Clarke为子域名提供的解决方案很好,但请注意,您需要包括文档。域名= "mydomain.com";在iframe页眉和父页眉中,如链接同源策略检查中所述
An important extension to the same origin policy implemented for JavaScript DOM access (but not for most of the other flavors of same-origin checks) is that two sites sharing a common top-level domain may opt to communicate despite failing the "same host" check by mutually setting their respective document.domain DOM property to the same qualified, right-hand fragment of their current host name. For example, if http://en.example.com/ and http://fr.example.com/ both set document.domain to "example.com", they would be from that point on considered same-origin for the purpose of DOM manipulation.