Konstantin Fedoseev
Konstantin Fedoseev

Reputation: 301

Call to function in parent from .JS file from inside iframe

I have JS file with uploader functionality. This file called from an iframe window. I need to show alerts to user according to his actions.

Here is what I've done and it's not works:

From JS file:

$('#btnUpload').on('click', function(){
    parent.CallToParent();
});

And from UploaderWindow call to:

function CallToParent()
{
   parent.ShowAlert();
}

And on main window:

function ShowAlert()
{
   alert('some alert');
}

Upvotes: 0

Views: 1174

Answers (2)

Salman
Salman

Reputation: 9447

I think you are doing it correct. Don't know if the parent.CallToParent() in the click event really refers to the function in the parent window. If it doesn't then you could do something like.

From JS file:

$(document).ready(function () {
    $('#btnUpload').on('click', function() {
        callParent();
    })
});

And from iframe:

<script type="text/javascript" src="/common/jq.js"></script>
<script type="text/javascript" src="c.js"></script>
<script>
    function callParent() {
        parent.fn();
    }
</script>

<input id="btnUpload" type="button" />

Main File

<script>
    function fn() {
        console.log('Parent function called');
    }
</script>

<iframe src="b.html"></iframe>

Upvotes: 1

Grant Thomas
Grant Thomas

Reputation: 45083

To my knowledge, there's no interoperability of scripts between these two contexts.

If you have control of the iframe contents then you could implement a 'middle-man' service to pipe messages.

Upvotes: 0

Related Questions