Invoking JavaScript code in an iframe from the par

2018-12-31 01:23发布

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 opposite is quite simple as you only need to call parent.functionName(), but unfortunately, I need exactly the opposite of that.

Please note that my problem is not changing the source URL of the iframe, but invoking a function defined in the iframe.

17条回答
春风洒进眼中
2楼-- · 2018-12-31 02:11

Try just parent.myfunction()

查看更多
闭嘴吧你
3楼-- · 2018-12-31 02:12

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.

查看更多
零度萤火
4楼-- · 2018-12-31 02: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','*')
查看更多
无与为乐者.
5楼-- · 2018-12-31 02:14

Use following to call function of a frame in parent page

parent.document.getElementById('frameid').contentWindow.somefunction()
查看更多
浮光初槿花落
6楼-- · 2018-12-31 02:15

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 :)

查看更多
登录 后发表回答