Home  >  Q&A  >  body text

iframe cross-domain problem

<p>Suppose I have a website called example.com with an iframe embedded in the iframe.net domain, now I want to read the content of the iframe and pass some parameters to display a text message. Like to use the username Hi. </p> <p>Now the problem is that this cannot establish a connection between the two or even get the innerHTML of the iframe which I use below</p> <pre class="brush:php;toolbar:false;">document.getElementById('myframe').contentWindow.document.body.innerHTML;</pre> <p>It throws the error "Permission to access property is denied"</p> <p>Does anyone know how to read and write across cross-domain platforms</p>
P粉939473759P粉939473759445 days ago502

reply all(2)I'll reply

  • P粉092778585

    P粉0927785852023-08-25 08:07:08

    In Internet Explorer 8, events passed as parameters may be null, which is why you need to access the events differently:

    In frame.html:

    window.onmessage = function(event) {
       var evt = event || window.event;
       evt.source.postMessage('Message from iFrame', evt.origin);
    };

    On main.html:

    window.onmessage = function(event) {
       var evt = event || window.event;
       alert(evt.data);
    };

    The event is triggered the same way as presented by Rob W:

    document.getElementById('frameId').contentWindow.postMessage('message','*');

    reply
    0
  • P粉670838735

    P粉6708387352023-08-25 00:50:36

    If you have no control over the website being framed, there is no way to circumvent the cross-origin policy.

    If you have control over both sites, you can use the postMessage method of transferring data across domains. A very basic example:

    // framed.htm:
    window.onmessage = function(event) {
        event.source.postMessage(document.body.innerHTML, event.origin);
    };
    
    // Main page:
    window.onmessage = function(event) {
        alert(event.data);
    };
    
    // Trigger:
    // <iframe id="myframe" src="framed.htm"></iframe>
    document.getElementById('myframe').contentWindow.postMessage('','*');

    reply
    0
  • Cancelreply