I'm creating a iframe that is same domain, just a different subdomain, and i want to get a link src from inside the iframe with "document.getElementsByTagName('a')[5];"
How can I do this?
I'm creating a iframe that is same domain, just a different subdomain, and i want to get a link src from inside the iframe with "document.getElementsByTagName('a')[5];"
How can I do this?
To get around the same-origin policy, you should make use of document.domain
- in both the main page and the iframe, set it to the domain of the main page. So, if your main page is on the domain foo.com
and your iframe loads from bar.foo.com
, in both the pages, set document.domain = 'foo.com'
. You must do this for the main page, even if you set it to the same value - see note below.
Now, to get the element, you may do what's described in this SO answer:
var iframe = document.getElementById('iframeId');
var innerDoc = iframe.contentDocument || iframe.contentWindow.document;
Update
The MDC has this to say:
Mozilla distinguishes a document.domain property that has never been set from one explicitly set to the same domain as the document's URL, even though the property returns the same value in both cases. One document is allowed to access another if they have both set document.domain to the same value, indicating their intent to cooperate, or neither has set document.domain and the domains in the URLs are the same (implementation). Were it not for this special policy, every site would be subject to XSS from its subdomains (for example, https://bugzilla.mozilla.org could be attacked by bug attachments on https://bug*.bugzilla.mozilla.org).
Thus, both the iframe and the including page must set the same value for document.domain