Question

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?

Was it helpful?

Solution 2

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();
}

OTHER TIPS

function check() {
    try { 
        location.host; // if I error, doStuff() is never hit. 
        doStuff();
    } catch( e ) {
        setTimeout(check, 5000);
    }
}

Using a try / catch statement should solve this issue for you. There are likely other ways around this, however after reviewing your question this was the first that came to mind.

Another alternative is to listen for the onload event from the iframe. This (in chrome at least) fires each time the iframe page changes. http://jsfiddle.net/rlemon/DwVJX/1/ here is a quick demo. In the iframe click on the jsFiddle logo to go back to the homepage. I understand this doesn't tell you IF you're on the right domain or not, but in conjunction with the try/catch this eliminates the need for a timer.

I think what you are currently doing is the only way to reliably detect whether an iframe is or isn't on a page hosted on your parent page's domain.

Most iframe properties are inaccessible (throw an exception when accessed) while the iframe is on a different domain than the parent. An exception is actually an indication that the iframe IS NOT on your site, so simply catch the exception and try again. If no exception is thrown, the iframe is on a page that is in the same domain as it's parent.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top