Access parent window from iframe (cross-domain)

后端 未结 5 971
长情又很酷
长情又很酷 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:34

    If I were you I would check out window.postMessage. It may do what you want:

    For reference see the following:

    • MDN - Window.postMessage
    • https://stackoverflow.com/a/3076648/296889 - see the Window.postMessage section
    0 讨论(0)
  • 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

    0 讨论(0)
  • but you can change the src attribute of the iframe (adding a #hashtag for example) and listen to the onhashchange event in the child window. Given that you're in position to change both pages.

    0 讨论(0)
  • 2020-12-06 02:39

    set a variable/item in sessionStorage and use it on both sides as you wish. localStorage can do it for longer times.

    security risk is someone uses and manipulates this to hijack your side. BUT if someone wants to do so - there will allways be a possibility.

    Remember: Life finds a way... ;-)

    0 讨论(0)
  • 2020-12-06 02:45

    If I understand correctly, all modern browsers do now allow to do this. So I'm here to find the best solution.

    This is your solution. What you're asking is not possible.

    See related questions:

    • How to access parent Iframe from JavaScript
    • <iframe> javascript access parent DOM across domains?
    • Cross-domain access in iframe from child to parent

    EDIT

    As mentioned in the comments below, @JeremysAwesome's answer offers a method that would allow cross-domain requests under certain circumstances. See the SO question below for more information.

    Ways to circumvent the same-origin policy

    0 讨论(0)
提交回复
热议问题