www.webdeveloper.com
Results 1 to 2 of 2

Thread: iframe accessing variables

  1. #1
    Join Date
    Mar 2011
    Posts
    43

    iframe accessing variables

    Hey

    is it possible to access javascript variables in an iframe src page from the parent page, or vice versa. How do you do this? What about the DOM?

    thanks

  2. #2
    Join Date
    Aug 2011
    Location
    Gdynia
    Posts
    8
    It is possible but only if the iframed page and its parent are loaded from the same domain... otherwise it's not allowed to access the parent form iframe and vice versa.

    But let's assume that domains are the same...


    Accessing parents variables (or functions)
    1. define some container object in the window namespace, e.g.
      Code:
      window.sharedVars = {}
    2. all the functions or variables you want to share put their references also to the window.exportVars, e.g.
      Code:
      function hello(){
        alert("Hello iframe!");
      }
      window.sharedVars.sayHello = hello;
    3. in the iframed page access the variables as following:
      Code:
      //call the parent's function
      window.parent.sharedVars.sayHello();
      //set a variable in parents namespace
      window.parent.sharedVars.responseText = "Hello parent!";


    Accessing iframed variables (or functions)
    1. make sure your iframe has a name attribute (e.g. name="example-frame")
    2. then you can access the iframe object by window.frames['example-frame']
    3. same as in parent define some container object in the window namespace, e.g.
      Code:
      window.sharedVars = {}
    4. all the functions or variables in your iframe you want to share with parent put their references also to the window.exportVars, e.g.
      Code:
      function iframedHello(){
        alert("Hello parent!);
      }
      window.sharedVars.sayHello = iframedHello;
    5. in the parent page access the variables as following:
      Code:
      //call the iframed function
      window.frames['iframe-name'].sharedVars.iframedHello();
      //set a variable in the iframe namespace
      window.frames['iframe-name'].sharedVars.responseText = "Hello parent!";


    NOTICE: This approach won't work if you open your test page from the file system. It will only work loaded from the server - remote or just form your localhost (e.g. localhost/test.html)
    Last edited by desiter; 08-29-2011 at 11:31 AM.
    Can object-oriented JavaScript be more legible?

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles