Invoking JavaScript code in an iframe from the parent page

后端 未结 17 1830
栀梦
栀梦 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:13

    Some of these answers don't address the CORS issue, or don't make it obvious where you place the code snippets to make the communication possible.

    Here is a concrete example. Say I want to click a button on the parent page, and have that do something inside the iframe. Here is how I would do it.

    parent_frame.html

    
    
    function call_button_inside_frame() {
       document.getElementById('my_iframe').contentWindow.postMessage('foo','*');
    }
    

    iframe_page.html

    window.addEventListener("message", receiveMessage, false);
    
    function receiveMessage(event)
        {
          if(event) {
            click_button_inside_frame();
        }
    }
    
    function click_button_inside_frame() {
       document.getElementById('frame_button').click();
    }
    

    To go the other direction (click button inside iframe to call method outside iframe) just switch where the code snippet live, and change this:

    document.getElementById('my_iframe').contentWindow.postMessage('foo','*');
    

    to this:

    window.parent.postMessage('foo','*')
    

提交回复
热议问题