2

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

Ahmed Kamal
  • 1,478
  • 14
  • 27
  • 1
    If you can [control both pages](https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy), yes, otherwise no. – Teemu Oct 30 '14 at 11:42

2 Answers2

3

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.

jAndy
  • 231,737
  • 57
  • 305
  • 359
  • In this case , they will be hosted on the same domain , what should be done then ? – Ahmed Kamal Oct 30 '14 at 12:07
  • 1
    @AhmedKamal In that case, you can just access the `window` repectively `document` objects from each other. Either by accessing `parent` from the iFrame or `iframe.contentWindow` from the parent. There you have an option to access whatever JS related data. – jAndy Oct 30 '14 at 12:10
  • I tried to do so but the frame web site has different port from the asp.net parent web app. when I tried to access the parent from the child , I got this error Uncaught SecurityError: Blocked a frame with origin "http://localhost:63430" from accessing a frame with origin "http://localhost". Protocols, domains, and ports must match. – Ahmed Kamal Oct 30 '14 at 12:19
  • 1
    different port means, you're out of luck. Then, read the article about postMessage, SOP will not allow you any other. – jAndy Oct 30 '14 at 12:23
  • Ok , Thanks a lot for your support , I have accepted your answer :) – Ahmed Kamal Oct 30 '14 at 12:27
0

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

Community
  • 1
  • 1
Avisek Chakraborty
  • 8,229
  • 10
  • 48
  • 76