How to access parent Iframe from JavaScript

后端 未结 9 1520
梦毁少年i
梦毁少年i 2020-11-22 07:50

Well, I have an IFrame, which calls a same domain page. My problem is that I want to access some information from this parent Iframe from this called page (from JavaScript).

9条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-22 08:46

    I would recommend using the postMessage API.

    In your iframe, call:

    window.parent.postMessage({message: 'Hello world'}, 'http://localhost/');
    

    In the page you're including the iframe you can listen for events like this:

    window.addEventListener('message', function(event) {
          if(event.origin === 'http://localhost/')
          {
            alert('Received message: ' + event.data.message);
          }
          else
          {
            alert('Origin not allowed!');
          }
    
        }, false);
    

    By the way, it is also possible to do calls to other windows, and not only iframes.

    Read more about the postMessage API on John Resigs blog here

提交回复
热议问题