简体   繁体   中英

Can't call functions in parent from iframe

I'm trying to make a call to 2 functions setListener(); and addNewBox(); from within an iframe.

I've looked everywhere and tried everything and I can't get it to work.

I don't have access to the head of the parent because it is being constructed in chunks through php require.

This is a rough mockup of what the parent file looks like.

<head>
<?php require "head.html" ?>
</head>
<body>
<?php require "content.html" ?>
</body>

content.html mockup:

<!-- a bunch of boring divs -->
<iframe src="image_editor.html"></iframe>
<script> /* random ajax */ </script>
<script>
$(document).ready(function(e) {
    //init
    setListener();
    addNewBox();

    function setListener()
    {
            //MAGIC HAPPENS
        }

        function addNewBox()
    {
            //GREATER MAGIC HAPPENS
        }
}
</script>

image_editor.html mockup:

<body>
<form id="image_form">
<input type="submit" value="Submit"/>
</form>
<script>
$(document).ready(function(e) {
    $("#image_form").submit(function(e) {
            //MAGIC HAPPENS HERE

            //re-adds listeners
            window.parent.addNewBox();
            window.parent.setListener();
        }
</script>
</body>

I have tried every solution I could find online, from using top, to re-declaring the functions in parent in public format (window.myFunction = function() { };).

I would appreciate any advice.

Thanks

UPDATE: After some debugging it seems that the reason the calls aren't working is because execution stop one line before them. Somehow this line "$(".new", window.parent.document).remove();" breaks everything. I now have to figure that one out. I appreciate all your help.

This happens at least because setListener() and addNewBox() are not in the global scope of window.parent . To fix this you need to move them out of $(document).ready(function(e) {...}()) .

This is because they are in $(document).ready(function(){});

You can fix it like this:

$(window.parent).bind(setListener);
$(window.parent).bind(addNewBox);

Hope it helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM