Invoking JavaScript Code in an Iframe from the Parent Page

Invoking JavaScript code in an iframe from the parent page

Assume your iFrame's id is "targetFrame" and the function you want to call is targetFunction():

document.getElementById('targetFrame').contentWindow.targetFunction();

You can also access the frame using window.frames instead of document.getElementById.

// this option does not work in most of latest versions of chrome and Firefox
window.frames[0].frameElement.contentWindow.targetFunction();

Calling a parent window function from an iframe

<a onclick="parent.abc();" href="#" >Call Me </a>

See window.parent

Returns a reference to the parent of the current window or subframe.

If a window does not have a parent, its parent property is a reference to itself.

When a window is loaded in an <iframe>, <object>, or <frame>, its parent is the window with the element embedding the window.

Call parent Javascript function from inside an iframe

Try just parent.myfunction(). Also be 100% sure that the parent.js is included in your parent document.

Calling javascript function in iframe

Use:

document.getElementById("resultFrame").contentWindow.Reset();

to access the Reset function in the iframe

document.getElementById("resultFrame")
will get the iframe in your code, and contentWindow will get the window object in the iframe. Once you have the child window, you can refer to javascript in that context.

Also see HERE in particular the answer from bobince.

How to Call Parent Window JavaScript Function inside iframe

You cannot access the DOM of a page loaded in a frame in a different origin. This is blocked for security reasons (imagine a random website you visited opening your web mail service in a hidden iframe and you can see why).

The closest you can come, and then only if you control both websites, is to pass messages between them using the web messaging api.

In one page, write a function to handle the messages and then add it as a message event listener.

function receiveMessage(event)
{
alert(event.data);
}

addEventListener("message", receiveMessage, false);

In the other, send the message:

parent.postMessage("This is a message", "*");

See MDN for more information



Related Topics



Leave a reply



Submit