Calling a parent window function from an iframe

I recently had to find out why this didn't work too.

The javascript you want to call from the child iframe needs to be in the head of the parent. If it is in the body, the script is not available in the global scope.

<head>
    <script>
    function abc() {
        alert("sss");
    }
    </script>
</head>
<body>
    <iframe id="myFrame">
        <a onclick="parent.abc();" href="#">Click Me</a>
    </iframe>
</body>

Hope this helps anyone that stumbles upon this issue again.


<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.


Window.postMessage()

This method safely enables cross-origin communication.

And if you have access to parent page code then any parent method can be called as well as any data can be passed directly from Iframe. Here is a small example:

Parent page:

if (window.addEventListener) {
    window.addEventListener("message", onMessage, false);        
} 
else if (window.attachEvent) {
    window.attachEvent("onmessage", onMessage, false);
}

function onMessage(event) {
    // Check sender origin to be trusted
    if (event.origin !== "http://example.com") return;

    var data = event.data;

    if (typeof(window[data.func]) == "function") {
        window[data.func].call(null, data.message);
    }
}

// Function to be called from iframe
function parentFunc(message) {
    alert(message);
}

Iframe code:

window.parent.postMessage({
    'func': 'parentFunc',
    'message': 'Message text from iframe.'
}, "*");
// Use target origin instead of *

UPDATES:

Security note:

Always provide a specific targetOrigin, NOT *, if you know where the other window's document should be located. Failing to provide a specific target discloses the data you send to any interested malicious site (comment by ZalemCitizen).

References:

  • Cross-document messaging
  • Window.postMessage()
  • Can I Use