Pass a Javascript Object to an HTML iframe (as an Object)

Viewed 8516

A MainWindow creates a JavaScript object that the ChildWindow needs to utilize utilize.

My MainWindow.html looks like this at the moment

<html>
  <body>
    <script>
      var varObject = {type:"Error", message:"Lots"};
    </script>
    <iframe class="child" src="ChildWindow.html"></iframe>
  </body>
</html>

The ChildWindow.html looks like this

<html>
  <body>
    <script>
      console.log(varObject.type); // goal is to log "Error"
    </script>
  </body>
</html>

The ChildWindow is trying to use the object that was created in the MainWindow which of course it can't because I don't yet know how to pass it.

I've tried to Google this but most of the solutions I found involved passing the values as strings instead of as a variable.

3 Answers

One can simply pass the object by assigning the object to the window of the iframe.

in the parent window:

var frame = document.querySelector("iframe");
frame.contentWindow.object_of_interest = object_of_interest;

in the iframe'ed window

console.log(window.object_of_interest);

Please have a look at following code :

<html>
  <body>
    <script>
      var varObject = {type:"Error", message:"Lots"};
      var child = document.getElementsByClassName("child")[0];
      var childWindow = child.contentWindow;
      childWindow.postMessage(JSON.stringify(varObject),*);
    </script>
    <iframe class="child" src="ChildWindow.html"></iframe>
  </body>
</html>

In ChildWindow.html

<html>
  <body>
    <script>
      function getData(e){
        let data = JSON.parse(e.data);
        console.log(data);
      }
      if(window.addEventListener){
        window.addEventListener("message", getData, false);
      } else {
        window.attachEvent("onmessage", getData);
      }
    </script>
  </body>
</html>

Hope it helps :)

Related