1

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 Answer 1

1

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();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.