Can I access contents of an iframe from a subdomain if I use www. on the main domain?

后端 未结 1 1655
终归单人心
终归单人心 2021-02-05 16:13

I\'m trying to access and edit the contents of an iframe. The iframe points to a page on a subdomain on my own domain. This is the javascript code I\'m using, although it doesn\

相关标签:
1条回答
  • 2021-02-05 16:58

    Same-Origin-Policy requires the exact same hostname by default.

    To tell it not to, set:

    document.domain= 'domain.com';
    

    from script in both the parent (www.) document and the iframe (example.) document.

    Note that setting an onload of a statically-written iframe (or image) from script is unreliable, as it is conceivable that the iframe might get completely loaded in between the time the parser reads the iframe tag and when it reads the script tag that sets the onload.

    To avoid this, either include the event handler as an inline ‘<iframe onload="doSomething()"’ attribute (one of the few places where inline event handling has some purpose), or, if acceptable for accessibility, create the iframe element itself from script, setting the onload before writing the src and adding it to the page.

    0 讨论(0)
提交回复
热议问题