I want to read window.top.location.origin
from inside an iFrame.
The parent and iFrame are on different HTTPS domains.
Trying to access that throws a security error in Chrome for example.
[DOMException: Blocked a frame with origin "..." from accessing a cross-origin frame.]
Is it at all possible to do that without triggering the error?
I need window.top
's origin because I send different postMessages based on that origin.
I want to read window.top.location.origin
from inside an iFrame.
The parent and iFrame are on different HTTPS domains.
Trying to access that throws a security error in Chrome for example.
[DOMException: Blocked a frame with origin "..." from accessing a cross-origin frame.]
Is it at all possible to do that without triggering the error?
I need window.top
's origin because I send different postMessages based on that origin.
- what kind of error do you get in the console? – user123_456 Commented Oct 3, 2014 at 17:36
- I'll update the question. – Francisc Commented Oct 3, 2014 at 17:38
- you need to get a message from the parent, and then you can see the origin from the message properties. it's like replying to an email you didn't used to have the address for. – dandavis Commented Oct 3, 2014 at 18:07
- Yup, I know that. But I'm trying do initiate the munication from the child iFrame. e.g. "I'm loaded and ready to listen for events" – Francisc Commented Oct 3, 2014 at 19:18
2 Answers
Reset to default 6I know this is old, but maybe it helps others:
The full Parent URL will appear to the <iframe/>
as document.referrer
. With that, you can parse it locally to find the URL specifics you may need.
if (document.referrer !== location.href) {
let foo = document.createElement('a');
foo.href = document.referrer;
console.log('origin is:', foo.origin);
}
Of course, this is thanks to the anchor tag's built-in parsing. Hidden gem~!
Because of the same-origin policy, JavaScript in an iframe from a different origin will not be able to municate with its parent frame. If you have access to the server that serves the iframe, you can enable CORS, otherwise I think you are out of luck