Why am I getting a TypeError when trying to call a function in an iFrame from the parent page?
I have a page (parent) with an iFrame (child) embedded in it, the iFrame contains a javascript function that I need to call from the parent. The page are on different domains, I don't know if that's the issue th开发者_Go百科ough. This is my code on the parent page:
<script type="text/javascript">
function SaveChanges() {
var iFrame = document.getElementById("iframeSite");
iFrame.contentWindow.ExecuteSave();
}
</script>
...and my code on the child page:
<script type="text/javascript">
function ExecuteSave() {
alert("test1");
}
</script>
When I call "SaveChanges" in the parent it errors at the line where it attempts to call "ExecuteSave".
Uncaught TypeError: Property 'ExecuteSave' of object [object DOMWindow]
is not a function
I've tried pretty much every variation of calling a child iFrame's function but still receive the same error.
Because the iframes are in different domains, you won't be able to directly call between them. This would be a violation of the Same Origin Policy.
There is a sanctioned way for having an iframe and a parent communicate. It's called postMessage()
.
Hope this helps!
精彩评论