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.
1 Answer 1
Is not possible, for security reasons you can't access other domain/host/port content or src url of an iframe
8 Comments
.postMessage() was for - to bypass CORS restrictions?.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