Eki Eqbal
Eki Eqbal

Reputation: 6057

How to trigger an event from parent window based on iframe content?

I'm creating a widget using iframe, and I want to hide the iframe in a specific event.

Let's say main.html file has:

<div id="my_widget">
  <iframe src="www.mysite.com/main.html" width="50%" frameborder="0" height="550" id="my_iframe">Error uploading the frame.</iframe>
</div>

widget.html file contains:

<div id="widget-status-div" status="success"></div> 

I tried to add some script by end of the widget.html file to access parent window (main.html) like:

<script type="text/javascript">       
    setTimeout(function(){
      parent.$("#my_widget").fadeOut(300, function() { parent.$("#my_widget").remove(); });
    }, 3000);       
</script>

But unfortunately it didn't work.

Another thing I tried to do, is to set setInterval(check_iframe, 5000) at parent window(main.html) to keep checking widget-status-div div at iframe every 5 seconds, but the problem is that I can't check the content of the iframe somehow (or maybe I'm doing it wrong).

Any help would be highly appreciated.

Thanks

Upvotes: 0

Views: 5077

Answers (1)

Simon
Simon

Reputation: 230

This will fail most likley due to the same-origin-policy. It restricts JavaScript access from one protocol and domain to another.

Same Origin Policy results

For more information about this you can check out the wiki entry

To achieve cross origin communication you can use the messaging API defined here.

With this api you can define an event listener on one file and a trigger in the other.

Listen to messages:

window.addEventListener("message", receiveMessage, false);

function receiveMessage(event)
{
  if (event.origin !== "http://example.org:8080")
    return;

  // ...
}

Post a message to another document:

var parentWindow = window.parent;

// When the popup has fully loaded, if not blocked by a popup blocker:

// This does nothing, assuming the window hasn't changed its location.
parentWindow.postMessage("The user is 'bob' and the password is 'secret'",
                  "https://secure.example.net");

You can checkout the complete example in the MDN Documentation

Upvotes: 1

Related Questions