Getting Javascript variable from a source script on an html page loaded in an iframe

Viewed 24

Following up from this question here: Accessing JavaScript variable in an iframe, from the parent window on same domain

For purposes of posting something testable here, I have a src.js file set up like:

var foo = {"foo":"bar"};

then I can an HTML page test1.html with this line in the head:

<script src="src.js" type="text/javascript"></script>

Then I have another HTML page test2.html, with

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

How can I access foo from test2.html? I tried the following but could not find foo (running this on button click from a div in test2.html)

  console.log("foo: " + typeof foo);
  console.log("foo: " + window.foo);
  console.log("Frame window: " + window.frames[0].window); //this works
  console.log("Sections: " + window.frames[0].window.foo);

Note: In the iframe, foo is definitely there

1 Answers

Here is what eventually worked for me. In JS library:

const foo = {"foo":"bar"};

window.getFoo = function() {
  return foo;
}

On page with iFrame (test2.html):

  var iframe = document.getElementById("mainPanel"); //mainPanel is the id of the iframe
  var iWindow = iframe.contentWindow;
  var foo = iWindow.getFoo();
Related