Search code examples
javascriptjqueryhtmliframesame-origin-policy

Access subdomain iframe url from other subdomain page


I'm trying to access the iframe contentWindow property for an iframe which is hosted on a subdomain within the same domain. So I have this code on a.domain.com (which hosts the role of parent page):

<script type="text/javascript">
    $(document).ready(function () {        
        $('#frame').load(function () {            
            var iframe = document.getElementById('frame');            
            if (iframe) {
                 var item = iframe.contentWindow;             
                if (item.indexOf("Completed") != -1) {
                    window.location.href = '../Home/Completed/';                   
                } else {
                    window.location.href = '../Home/PayAgain/';
                }
            }            
        });
    });
</script>

The actual iframe content sits on b.domain.com and I want to get the current page in the iframe.

I see some examples that I need to set document.domain = "domain.com" in both a.domain.com and b.domain.com but for example what exactly do I need to set in a.domain.com and b.domain.com regarding document.domain?

In which pages in b.domain.com I need to set the document.domain value?


Solution

  • I was in this same situation and I found that using window.postMessage was a much better way to communicate between the frames: https://developer.mozilla.org/en-US/docs/Web/API/Window.postMessage

    If you want to use the method you mentioned, every page that loads within the frame will need to manually set document.domain on load. The parent page will also need to set it. It is just a built-in javascript property of the document object.