Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 841
TheLovelySausage Avatar asked Mar 17 '16 09:03

TheLovelySausage


People also ask

How do I pass data into iframes?

The usual solution is to use window. parent in the frame to get "up" (into the document which contains the iframe tag). Now you can call any method in the container document. This method can manipulate the frame (for example call some JavaScript in the frame with the parameters you need).

Can JavaScript interact with iframe?

On this page, two iframes interact with each other using JavaScript. First we show how one iframe can get references to the other iframe and the document inside it. Then we provide an example which demonstrates one iframe accessing and modifying the other's properties, objects, and content.

Why you shouldn't use iframes?

Iframes Bring Security Risks. If you create an iframe, your site becomes vulnerable to cross-site attacks. You may get a submittable malicious web form, phishing your users' personal data. A malicious user can run a plug-in.


1 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);
like image 132
Ulad Kasach Avatar answered Nov 15 '22 00:11

Ulad Kasach