Possible to get an iframe's url cross-domain?

僤鯓⒐⒋嵵緔 提交于 2021-01-27 18:27:48

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!