Invoking JavaScript code in an iframe from the parent page

后端 未结 17 1799
栀梦
栀梦 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

    In the IFRAME, make your function public to the window object:

    window.myFunction = function(args) {
       doStuff();
    }
    

    For access from the parent page, use this:

    var iframe = document.getElementById("iframeId");
    iframe.contentWindow.myFunction(args);
    
    0 讨论(0)
  • 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

    <button id='parent_page_button' onclick='call_button_inside_frame()'></button>
    
    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','*')
    
    0 讨论(0)
  • 2020-11-21 07:15

    If you want to invoke the JavaScript function on the Parent from the iframe generated by another function ex shadowbox or lightbox.

    You should try to make use of window object and invoke parent function:

    window.parent.targetFunction();
    
    0 讨论(0)
  • 2020-11-21 07:18

    Same things but a bit easier way will be How to refresh parent page from page within iframe. Just call the parent page's function to invoke javascript function to reload the page:

    window.location.reload();
    

    Or do this directly from the page in iframe:

    window.parent.location.reload();
    

    Both works.

    0 讨论(0)
  • 2020-11-21 07:19

    Continuing with JoelAnair's answer:

    For more robustness, use as follows:

    var el = document.getElementById('targetFrame');
    
    if(el.contentWindow)
    {
       el.contentWindow.targetFunction();
    }
    else if(el.contentDocument)
    {
       el.contentDocument.targetFunction();
    }
    

    Workd like charm :)

    0 讨论(0)
  • 2020-11-21 07:20
           $("#myframe").load(function() {
                alert("loaded");
            });
    
    0 讨论(0)
提交回复
热议问题