Access parent URL from iframe

Okay, I have a page on and on this page I have an iframe. What I need to do is on the iframe page, find out what the URL of the main page is.

I have searched around and I know that this is not possible if my iframe page is on a different domain, as that is cross-site scripting. But everywhere I've read says that if the iframe page is on the same domain as the parent page, it should work if I do for instance:

parent.document.location
parent.window.document.location
parent.window.location
parent.document.location.href

... or other similar combos, as there seems to be multiple ways to get the same info.

Anyways, so here's the problem. My iframe is on the same domain as the main page, but it is not on the same SUB domain. So for instance I have

http:// www.mysite.com/pageA.html

and then my iframe URL is

http:// qa-www.mysite.com/pageB.html

When I try to grab the URL from pageB.html (the iframe page), I keep getting the same access denied error. So it appears that even sub-domains count as cross-site scripting, is that correct, or am I doing something wrong?

169
задан sideshowbarker 2 February 2019 в 16:42
поделиться

2 ответа

Вы правы. Поддомены по-прежнему считаются отдельными доменами при использовании iframe. Можно передавать сообщения с помощью postMessage (...) , но другие JS API намеренно недоступны.

Также возможно получить URL в зависимости от контекста. См. Другие ответы для более подробной информации.

19
ответ дан 23 November 2019 в 20:49
поделиться

Для страниц на одном домене и разных поддоменах можно установить свойство document.domain через javascript.

И родительский фрейм, и iframe должны установить свой document.domain на что-то общее между ними.

т.е. www.foo.mydomain.com и api.foo.mydomain.com могут использовать либо foo.mydomain.com, либо просто mydomain. com и быть совместимыми (нет, вы не можете установить их оба на com, по соображениям безопасности...)

также обратите внимание, что document.domain - это улица с односторонним движением. Рассмотрим выполнение следующих трех утверждений по порядку:

// assume we're starting at www.foo.mydomain.com
document.domain = "foo.mydomain.com" // works
document.domain = "mydomain.com" // works
document.domain = "foo.mydomain.com" // throws a security exception

Современные браузеры также могут использовать window.postMessage для общения между источниками, но это не будет работать в IE6. https://developer.mozilla.org/en/DOM/window.postMessage

18
ответ дан 23 November 2019 в 20:49
поделиться
Другие вопросы по тегам:

Похожие вопросы: