Cross sub domain iframes and JavaScript

后端 未结 3 482
借酒劲吻你
借酒劲吻你 2020-12-01 07:58

I am working on a CMS site whose domain is:

http://www.acmssite.com

They have a sub-domain where they store a form system:

         


        
相关标签:
3条回答
  • 2020-12-01 08:20

    You can still bypass this issue with the help of YQL even though you don't have access to the header part of the receiving window. With the Postmessage method also you need to edit the recipient window script. But using this method you can load any iframe without touching their scripts. Check this out! jsfiddle-link

    <html>
    <iframe src="https://google.com/" width="500" height="300"></iframe>
    
    <script>
    var iframe = document.getElementsByTagName('iframe')[0];
    var url = iframe.src;
    var getData = function (data) {
        if (data && data.query && data.query.results && data.query.results.resources && data.query.results.resources.content && data.query.results.resources.status == 200) loadHTML(data.query.results.resources.content);
        else if (data && data.error && data.error.description) loadHTML(data.error.description);
        else loadHTML('Error: Cannot load ' + url);
    };
    var loadURL = function (src) {
        url = src;
        var script = document.createElement('script');
        script.src = 'https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20data.headers%20where%20url%3D%22' + encodeURIComponent(url) + '%22&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=getData';
        document.body.appendChild(script);
    };
    var loadHTML = function (html) {
        iframe.src = 'about:blank';
        iframe.contentWindow.document.open();
        iframe.contentWindow.document.write(html.replace(/<head>/i, '<head><base href="' + url + '"><scr' + 'ipt>document.addEventListener("click", function(e) { if(e.target && e.target.nodeName == "A") { e.preventDefault(); parent.loadURL(e.target.href); } });</scr' + 'ipt>'));
        iframe.contentWindow.document.close();
    }
    
    loadURL(iframe.src);
    </script>
    </html>
    
    0 讨论(0)
  • 2020-12-01 08:38

    In order for this to not be restricted by the same origin policy, you will probably need to do this in both the pages:

    document.domain = "acmssite.com";
    
    0 讨论(0)
  • 2020-12-01 08:38

    Yes it is.

    var iframe = document.getElementById("your-iframes-id").contentWindow.document;
    
    0 讨论(0)
提交回复
热议问题