Sunday, June 16, 2013

Javascript scope in HTML page which contains iframe

If a HTML page contains a “iframe”, what is the relationship between the javascripts in the two HTML pages in terms of function/variable scope?

2 comments:

  1. None.

    Each has it's own window object and js functions belong to a window object.

    If you want to access one from the other, you could for instance call a function on the parent from the iFrame using say

    parent.window.function or top.window.function if the iFrame is nested deeper. (the window part is not actually required as it is implicit)

    To access a function in the iFrame from the parent you could use say

    $('#myFrame').contentWindow.function

    This is using jQuery as an example but is just as easy with plain javascript

    Just make sure both the parent and the iFrame content are from the same domain, else you will get cross domain issues

    Regards

    ReplyDelete
    Replies
    1. Thanks, it makes sense.
      What about CSS? Does CSS in the parent affect elements inside the iFrame?
      I should be able to test it out, but just wondering from "theory" point of
      view.

      Regards

      Delete