Ahmed Kamal
Ahmed Kamal

Reputation: 1488

Talking between different javascript windows?

I have an asp.net web page that contains some javascript code and an Iframe element that views a different web page , my question is : are there any available ways to make these two windows communicate with each other ?

For eaxmple : I have a function called "Say HelloWorld" in the asp.net javascript code that should be invoked from the Iframe if a button in the Iframe page was clicked

Upvotes: 2

Views: 69

Answers (2)

Avisek Chakraborty
Avisek Chakraborty

Reputation: 8309

To Call parent from the child:

<script>
function calledFromChildIframe()  {
    alert("I am in Parent");
}
</script>

<iframe id="myFrame">
    ...........
    <a onclick="parent.calledFromChildIframe();" href="#" >Call Me </a>
</iframe>

Source: window.parent

For the opposite case, assume your iFrame's id is "targetFrame" and the function you want to call is targetFunction()

document.getElementById('targetFrame').contentWindow.targetFunction();

Source: here

Upvotes: 0

jAndy
jAndy

Reputation: 236102

Generally speaking, it makes a huge difference if you are dealing with windows which access the same domain/port/protocol combination or not. In other words, does the Same Origin Policy bother you in any way. Regardless of SOP, you should read this: HTML5 postMessage

If you are strictly dealing on the same domain, you don't really need magic like postMessage, but of course it wouldn't hurt you much either.

Upvotes: 3

Related Questions