2

How can I get the current url of an iframe on pageload if it is a cross-domain iframe?

Background - I'm trying to enable SSL on my website. However, my users need to be able load any url through an iframe. If they try to load an iframe with http protocol, it will refuse to load because the parent page is https.

I'd like to automatically detect if the iframe is http - and if it is, then redirect the parent page to http. However, with any method I've tried, I get CORS errors when accessing.

Here's my iframe:

<iframe id="myframe" src='https://apple.com' onload="this.contentWindow.parent.postMessage(this.contentWindow.document.location.protocol, parent.document.location);" width="800" height="600">
</iframe>

And here's my event listener:

window.addEventListener("message", receiveMessage, false);
function receiveMessage(event) {
 console.log(event.data)
}

I am able to receive plain strings as messages, but I'm not able to receive the protocol. My result using window.postMessage() is a CORS error, which I thought was supposed to allow cross-domain communication.

asked May 31, 2017 at 17:48

1 Answer 1

1

Is not possible, for security reasons you can't access other domain/host/port content or src url of an iframe

answered May 31, 2017 at 18:08
Sign up to request clarification or add additional context in comments.

8 Comments

Right - but I thought that's what .postMessage() was for - to bypass CORS restrictions?
but you can't send a message from a page you didn't wrote (like apple.com)
If I replace the first argument in .postMessage() with any string, then the page does receive the message from the iframe. So it definitely can send the message.. it just can't apparently read the document object. The iframe is capable of getting an http response from a server, so I would think it should have a way to send a harmless string with the url that it was redirected to? I'm sure you are correct, but I'll still wait a few hours before selecting best answer just in case someone has a clever trick
To access the location you need to be running inside the iframe script, that means you need apple to send the message for ex.
you can catch calls to console... but if you can this is terrible! I think the console writing it is the console from the iframe, so you can't
|

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.