0

I have an HTML page say main.html which has an iframe (say id="myFrame")showing child.html page. Both of these pages have a button called "Hide frame". The onclick of these buttons calls hideFrame() JS function which is declared in main.js file. The hideFrame() function just change the display of myFrame to "none".

function hideFrame(){
    document.getElementById("myFrame").style.display = "none";
}

The myFrame is in main.html file so the button in main.html when calls the hideFrame() function, it works. The frame gets hidden. But the same is not working if I call the function from child.html page.

How can I access this element (myFrame) form child.html page?

Srujan Barai
  • 2,295
  • 4
  • 29
  • 52
  • Possible duplicate of [Getting the document object of an iframe](http://stackoverflow.com/questions/7570496/getting-the-document-object-of-an-iframe) – Tony Chiboucas Jun 24 '16 at 16:30
  • 1
    Possible duplicate of [Calling a parent window function from an iframe](http://stackoverflow.com/questions/2161388/calling-a-parent-window-function-from-an-iframe) – jeffjenx Jun 24 '16 at 16:31

3 Answers3

1

Instead of using an iFrame, I would use jquery to load in segments of html files from other files.

If that is not possible, you could inject Javascript code into the child frame that references objects in the parent. Ex:

child:

<script>
    var x;
</script>

parent:

<script>
    $("#myFrame").x = function(){
        functionality / reference definitions
    }
</script>
iHowell
  • 2,263
  • 1
  • 25
  • 49
1

It took a while to understand what you are saying. From what I understand, you want to get access to an element on the top window from inside an iframe. Here is what to get access to the parent window:

var _parent = window.parent, _parent_dom = _parent.document;

Then to get access to an element from the parent page (in this case #myFrame):

var my_frame = _parent_dom.getElementById("myFrame");

1

you should use the main.html's window object to assign the function to. So instead of

function hideFrame(){
    document.getElementById("myFrame").style.display = "none";
}

you would do something like

window.hideFrame = function(){
    document.getElementById("myFrame").style.display = "none";
}

Now the function is globally scoped on main.html's window.

The child frame has it's own window object. You need access to the parent window object to call the function from child.html.

From main.html, you can call hideFrame normally on click onclick = hideFrame(), but in child.html, you should put onclick = window.parent.hideFrame()

Saharsh
  • 750
  • 7
  • 18