问题
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:
Is not possible, for security reasons you can't access other domain/host/port content or src url of an iframe
来源:https://stackoverflow.com/questions/44291523/possible-to-get-an-iframes-url-cross-domain