I found this sample from SO while browsing for my problem, but I want to know exactly how to use it in my scenario.
I have an iframe which is from another domain, and I want to detect when the iframe URL is changed from one to another page in that other domain. So, what I was thinking is to have something like this when the second page in the iframe is opened:
<script type="text/javascript">
$(document).ready(function() {
parent.postMessage("Second Page");
}
</script>
That's all I need, I just need to receive message that the iframe has different url. Now on the parent page, I'll might have something like this:
<script type="text/javascript">
$(document).ready(function() {
$('#frame').load(function () {
var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
var eventer = window[eventMethod];
var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";
// Listen to message from child window
eventer(messageEvent,function(e) {
var secondPageValue = // I want to get the value from the child page here, how can I do that?
},false);
});
});
</script>
I'm trying to use this postMessage option for the first time. Do I need to include some JS libraries such as jQuery on child side to make this work?
Sending some data from the child iframe to the parent window is also pretty simple. Whenever you embed an iframe, the iframe will have a reference to the parent window. You just need to use the PostMessage API to send data via the window. parent reference of the parent window.
All you have to do is first dispatch an event from the iframe to the parent that notifies the parent that the iframe is loaded (essentially a "ready message"). The parent will be listening for messages and if it receives the "ready message" event, it can then reply to the iframe with whatever message you want to send.
PostMessage() is a global method that safely enables cross-origin communication. It's a lot like Ajax but with cross-domain capability. We'll give it a whirl by setting up two-way communication between a web page and an iframe whose content resides on another server.
You need to set targetOrigin when using postMessage.
<script type="text/javascript">
$(document).ready(function() {
parent.postMessage("Second Page",'*');
}
</script>
Then on the host page.
function addAnEventListener(obj,evt,func){
if ('addEventListener' in obj){
obj.addEventListener(evt,func, false);
} else if ('attachEvent' in obj){//IE
obj.attachEvent('on'+evt,func);
}
}
function iFrameListener(event){
secondPageValue = event.data;
}
var secondPageValue='';
addAnEventListener(window,'message',iFrameListener);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With