Invoking JavaScript code in an iframe from the parent page

后端 未结 17 1792
栀梦
栀梦 2020-11-21 07:00

Basically, I have an iframe embedded in a page and the iframe has some JavaScript routines I need to invoke from the parent page.

Now the o

17条回答
  •  终归单人心
    2020-11-21 07:07

    If the iFrame's target and the containing document are on a different domain, the methods previously posted might not work, but there is a solution:

    For example, if document A contains an iframe element that contains document B, and script in document A calls postMessage() on the Window object of document B, then a message event will be fired on that object, marked as originating from the Window of document A. The script in document A might look like:

    var o = document.getElementsByTagName('iframe')[0];
    o.contentWindow.postMessage('Hello world', 'http://b.example.org/');
    

    To register an event handler for incoming events, the script would use addEventListener() (or similar mechanisms). For example, the script in document B might look like:

    window.addEventListener('message', receiver, false);
    function receiver(e) {
      if (e.origin == 'http://example.com') {
        if (e.data == 'Hello world') {
          e.source.postMessage('Hello', e.origin);
        } else {
          alert(e.data);
        }
      }
    }
    

    This script first checks the domain is the expected domain, and then looks at the message, which it either displays to the user, or responds to by sending a message back to the document which sent the message in the first place.

    via http://dev.w3.org/html5/postmsg/#web-messaging

提交回复
热议问题