Search code examples
javascriptiframecross-domain-policy

Detect when an iframe returns from a cross domain site


I have an iframe on my page that submits a form to a third party page. Once that third party is done with its calculation, it redirects back to my own site. I would like to detect when the iframe returns back to my own site.

My current approach is to use a timeout and check location.host of the iframe every 0.5 seconds. However, while the iframe is still on the third party site, I get a JS error, which I would like to avoid.

Is there a good way to figure out when the iframe's location is back on my own server without getting a JS error?


Solution

  • You could wrap your check in a try catch block. Alternatively you could have the page which is on your host 'call' the parent. (something like parent.notifyReady() ) That way you avoid having to use a setInterval

    You could base your logic on whether to call the parent or not by using the document.referrer property

    So on your third page you could have something like this:

    if(document.referrer.indexOf('otherdomain.com') != -1) {
        // script called via otherdomain.com
        parent.notifyReady();
    }