Access parent window from iframe (cross-domain)

后端 未结 5 988
长情又很酷
长情又很酷 2020-12-06 02:17

I\'ve encountered the task to access parent window from iFrame, if the window in iFrame was loaded from another domain. If I understand correctly, all modern browsers do now

5条回答
  •  感动是毒
    2020-12-06 02:35

    another way would be: setting the iframes src to a javascript: link 500-ish milliseconds after it loads. Example:

    setTimeout(function() {
      document.getElementsByTagName("iframe")[0].src = `javascript: 
          (function(){
              setInterval(function() {
              if (document.getElementById("is_closed").className.match(/true/g)) {
                  ...//see @jeremysawesome on how to do window.postMessage
              }
          })()`
    }, 500);
    

    While @jeremysawesome 's answer did work, this will work on an embedded iframe no matter the host domain, this is great when working with websites hosted on domains such as blogspot.com that don't allow you to change this type of content easily...

    Now obviously you'll still need to launch window.postMessage, more info on that can be found on @jeremysawesome 's answer

提交回复
热议问题