Click here to Skip to main content
14,738,282 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hello everyone -
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 2nd page in the iframe is opened:

<script type="text/javascript">
    $(document).ready(function() {
parent.postMessage("Second Page");

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?

I'm trying to use this postMessage option for first time, so every advice will be greatly appreciated. Also, do I need to include some JS libraries such as jquery on child side to make this work?

Thanks in advance, Laziale

1 solution

Refer my tip - Communication with Cross Domain IFrame - A Cross Browser Solution[^] to explore more on this technique.

You don't need to add jQuery file for the code which Posts and Receives message. But you have to include it for document.ready() and frame load events.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900